Objects and Sockets

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

Answer:
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
or
" +    "       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();  }}

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS