JMU
Object Transport
An Introduction with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


A Reminder
An Example

A Simple Class

javaexamples/serialization/Course.java
        import java.io.Serializable;


/**
 * A Course 
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class Course implements Serializable
{
    private static final long serialVersionUID = 1L;

    private int    number;
    private String department, title;

    /**
     * Explicit Value Constructor
     *
     * @param department  The department code
     * @param number      The course number
     * @param title       The course title
     */
    public Course(String department, int number, String title)
    {
       this.department = department;
       this.number     = number;
       this.title      = title;
    }

    /**
     * Get the course designation
     *
     * @return  The course designation
     */
    public String getDesignation()
    {
       return department+number;
    }

    /**
     * Get the course title
     *
     * @return  The course title
     */
    public String getTitle()
    {
       return title;
    }
}
        
An Example (cont.)

A More Complicated Class

javaexamples/serialization/CourseDatabase.java
        import java.io.Serializable;
import java.util.Iterator;
import java.util.HashMap;


/**
 * A database of Course objects
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class CourseDatabase implements Serializable
{
    private static final long serialVersionUID = 1L;

    private HashMap<String, Course>     db;

    /**
     * Constructor
     */
    public CourseDatabase()
    {
       db = new HashMap<String,Course>();
    }

    /**
     * Add a Course
     *
     * @param id       The identifier
     * @param course   The Course to add
     */
    public void add(String id, Course course)
    {
       db.put(id, course);
    }

    /**
     * Get the values (i.e., Course objects) in the database
     *
     * @return  The values
     */
    public Iterator<Course> iterator()
    {
       return db.values().iterator();
    }

    /**
     * Get a Course
     *
     * @param  department  The department identifier
     * @param  number      The course number
     * @return             The Course to get
     */
    public Course get(String department, int number)
    {
       return db.get(department+number);
    }

    /**
     * Remove a Course
     *
     * @param department   The department identifier
     * @param number       The course number
     */
    public void remove(String department, int number)
    {
       db.remove(department+number);
    }
}
        
The Obvious Approach to Object Transport
An Example Using TCP

A Server

javaexamples/serialization/CourseDatabaseServer.java
        import java.io.*;
import java.net.*;
import java.util.*;


/**
 * An example of sending a serialized object over the Internet
 * using TCP.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class CourseDatabaseServer 
{

    public static void main(String[] args)
    {
        Course               cross;
        
        CourseDatabase       db;
        ObjectOutputStream   out;
        ServerSocket         ss;
        Socket               s;

        cross = new Course("CS/MATH",227,"Discrete Mathematics");
       
        db = new CourseDatabase();
        db.add("CS139",  new Course("CS",139,"Algorithm Development"));
        db.add("CS227",  cross);
        db.add("CS240",  new Course("CS",240,"Data Structures and Algorithms"));
        db.add("MATH227", cross);

        try 
        {
            ss = new ServerSocket(9100);
            s = ss.accept();

            out = new ObjectOutputStream(s.getOutputStream());
            out.writeObject(db);
            out.flush();
            out.close();
        } 
        catch (Exception ex) 
        {
            ex.printStackTrace();
        }
    }
}
        
An Example Using TCP (cont.)

A Client

javaexamples/serialization/CourseDatabaseClient.java
        import java.io.*;
import java.net.*;
import java.util.*;

/**
 * An example of receiving a serialized object over the Internet
 * using TCP.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class CourseDatabaseClient
{

    public static void main(String[] args)
    {
       Course               course;
       CourseDatabase       db;
       Iterator<Course>     i;
       InetAddress          ip;
       Socket               s;
       ObjectInputStream    in;

       try 
       {
          ip = InetAddress.getByName("localhost");
          s = new Socket(ip, 9100);
          in = new ObjectInputStream(s.getInputStream());

          db = (CourseDatabase)in.readObject();
          in.close();
          s.close();

          i = db.iterator();
          while (i.hasNext()) 
          {
             course = i.next();
             System.out.println(course.getDesignation()+"\t"+
                                course.getTitle());
          }
       } 
       catch (Exception ex) 
       {
          ex.printStackTrace();
       }
    }
}
        
Using UDP for Object Transport
An Example Using UDP

A Receiver

javaexamples/serialization/CourseDatabaseReceiver.java
        import java.io.*;
import java.net.*;
import java.util.*;

/**
 * An example of receiving a serialized object over the Internet
 * using UDP.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class CourseDatabaseReceiver
{

    public static void main(String[] args) throws Exception
    {
        // Construct the UDP socket (for receiving)
        DatagramSocket socket = new DatagramSocket(22801);

        // Construct the UDP datagram
        byte[]         buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
        
        // "Wait" to receive a packet
        socket.receive(packet);

        // Construct a ByteArrayInputStream from the payload
        ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
        
        // Decorate the ByteArrayInputStream
        ObjectInputStream in = new ObjectInputStream(bais);

        // Deserialize
        CourseDatabase db = (CourseDatabase)in.readObject();
        in.close();

        // Use the deserialized CourseDatabase
        Iterator<Course> i = db.iterator();
        while (i.hasNext()) 
        {
             Course course = i.next();
             System.out.println(course.getDesignation()+"\t"+
                                course.getTitle());
        }
    }
}
        
An Example Using TCP (cont.)

A Sender

javaexamples/serialization/CourseDatabaseSender.java
        import java.io.*;
import java.net.*;
import java.util.*;


/**
 * An example of sending a serialized object over the Internet
 * using UDP
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class CourseDatabaseSender
{

    public static void main(String[] args) throws Exception
    {
        InetAddress ip;        
        if (args.length > 0) ip = InetAddress.getByName(args[0]);
        else                 ip = InetAddress.getByName("localhost");

        // Construct and populate a CourseDatabase
        Course cross = new Course("CS/MATH",227,"Discrete Mathematics");
       
        CourseDatabase db = new CourseDatabase();
        db.add("CS139",  new Course("CS",139,"Algorithm Development"));
        db.add("CS227",  cross);
        db.add("CS240",  new Course("CS",240,"Data Structures and Algorithms"));
        db.add("MATH227", cross);

        // Construct a ByteArayOutputStream
        ByteArrayOutputStream  baos = new ByteArrayOutputStream();

        // Decorate the ByteArrayOutputStream 
        ObjectOutputStream out = new ObjectOutputStream(baos);        

        // Serialize the CourseDatabase
        out.writeObject(db);
        out.close();

        // Construct the UDP packet
        byte[]         data = baos.toByteArray();
        DatagramPacket datagram = new DatagramPacket(data, data.length, 
                                                     ip, 22801);

        // Construct the UDP socket (for sending)
        DatagramSocket socket = new DatagramSocket();
        
        // Send the serialized CourseDatabase
        socket.send(datagram);
    }
}