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();  }}

Share the Post:
XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several

data fivetran pricing

Fivetran Pricing Explained

One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of

kubernetes logging

Kubernetes Logging: What You Need to Know

Kubernetes from Google is one of the most popular open-source and free container management solutions made to make managing and deploying applications easier. It has a solid architecture that makes

ransomware cyber attack

Why Is Ransomware Such a Major Threat?

One of the most significant cyber threats faced by modern organizations is a ransomware attack. Ransomware attacks have grown in both sophistication and frequency over the past few years, forcing

data dictionary

Tools You Need to Make a Data Dictionary

Data dictionaries are crucial for organizations of all sizes that deal with large amounts of data. they are centralized repositories of all the data in organizations, including metadata such as