Objects and Sockets

Objects and Sockets

Is it possible to send an object over a socket connection in Java?

Objects can be transmitted over a socket connection in the same way that they are written to a file. That is to say, you can serialize an object over any OutputStream using Java’s object serialization mechanism. I’ve covered object serialization before, so I’ll limit my answer to the details of serializing an object over a socket. The main thing to realize is that when you read the object, you must have the class of object accessible to the class loader. Otherwise, when you perform a readObject, a ClassNotFoundException will be thrown. If you can’t make the class accessible, you’ll have to create your own class loader and serialize the class first, before the object. Once you head down this road you are reinventing core features of RMI and should consider using it instead. The following example program demonstrates object serialization over a socket. Notice how the reading and writing of an object work exactly the same way as if we were reading or writing an object to a file; it’s just a matter of wrapping the socket streams. The program is meant to be run as a server on one machine and as a client on another machine. Start the server first and define a port number on which it should listen. Then run the client, giving it the server’s name and port number. The client will create a LabelFrame (from one of the other questions) and write it to the server which then displays it.

public class SocketSerialization {  public static final String USAGE =    "usage: SocketSerialization -server portnumber
" +    "       SocketSerialization -client server portnumber";  // Used by the client to write the object to he server  public static final void writeObject(String server, int port, Object obj)    throws IOException  {    Socket socket;    ObjectOutputStream output;    socket = new Socket(server, port);    output = new ObjectOutputStream(socket.getOutputStream());    output.writeObject(obj);    socket.close();  }  // Used by the server to read the object from the server  public static final Object readObject(int port) throws IOException {    ServerSocket server;    Socket socket;    ObjectInputStream input;    Object obj;    server = new ServerSocket(port);    socket = server.accept();    input = new ObjectInputStream(socket.getInputStream());    try {      obj = input.readObject();    } catch(ClassNotFoundException e) {      throw new IOException(e.getMessage());    }    socket.close();    return obj;  }  public static final void abort() {    System.err.println(USAGE);    System.exit(1);  }  public static final void main(String[] args) {    if(args.length == 2) {      if(!args[0].equals("-server"))        abort();      try {        Object obj = readObject(Integer.parseInt(args[1]));        Frame frame;        if(obj instanceof Frame) {          frame = (Frame)obj;          frame.addWindowListener(new WindowAdapter() {              public void windowClosing(WindowEvent e) {                Window window = e.getWindow();                window.setVisible(false);                window.dispose();                System.exit(0);              }            });          frame.pack();          frame.setVisible(true);        }      } catch(NumberFormatException e) {        abort();      } catch(IOException e) {        e.printStackTrace();      }    } else if(args.length == 3) {      if(!args[0].equals("-client"))        abort();      try {        LabelFrame frame;        frame = new LabelFrame();        frame.setText("Enigma");        frame.setAlignment(Label.CENTER);        writeObject(args[1], Integer.parseInt(args[2]), frame);      } catch(NumberFormatException e) {        abort();      } catch(IOException e) {        e.printStackTrace();      }    } else      abort();  }}

See also  How IoT Tech Will Transform Logistics

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist