How can I send objects across the network using sockets?

Tim Rohaly

Objects that implement Serializable may be sent across a socket connection using an ObjectInputStream and ObjectOutputStream combination.

Here are the steps to follow:

  1. First, define an object to send. As an example, we can define a class called Message to encapsulate our communications:
    public class Message implements Serializable {
        private int    senderID;
        private String messageText;
    
        public Message(int id, String text) {
            senderID    = id;
            messageText = text;
        }
        public String getText() {
            return messageText;
        }
    }
    
  2. Next, instantiate the object, wrap the socket's streams in object streams, then send the message across the socket:
    Message sayhey = new Message("123456789", "Hello");
    
    Socket socket = new Socket(host, port);
    ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
    
    out.writeObject(sayhey);
    
  3. On the other side of the socket, the message can be retrieved and used by invoking methods on the returned object:
    ObjectInputStream in  = new ObjectInputStream(socket.getInputStream());
    Message messageObject = (Message) in.readObject();
    String messageText = messageObject.getText();
    
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact