Sending objects via sockets

The only socket programming I've done in the past is simple text streams. I am wondering what is the most efficient way to send something like a Java object through a socket.

For example, if I have the following Employee class (Dependent will be a simple class consisting of dependent information):

public class Employee { private String name; private double salary; private ArrayList<Dependent> dependents; } 

Should I just make the Employee object Serializable and send the instances via the socket. Or should I write an xml file containing information about employees and send it? Any guidance would be greatly appreciated. Or is there some completely different and better way? Thanks!

+4
source share
3 answers

If you are only sending data through the Java JVM, then any choice is possible.

A textual representation (XML, JSON, or custom) has several advantages:

  • easier to make it compatible between Java and other languages
  • it is less fragile in the face of version changes or several different versions of your code at each end of the socket.
  • It is much easier to check and debug.

Depending on the format, this may be slightly slower, but it is often not significant.

+3
source

If you are not necessarily tied to using XML, you can also try JSON. The google-gson library makes this very trivial. To serialize the code, this is simple: -

 Employee employee = new Employee(); ... Gson gson = new Gson(); String json = gson.toJson(employee); 

And to deserialize the String at the other end: -

 String socketDataAsString = null; ...<read from socket>... Gson gson = new Gson(); Employee employee = gson.fromJson(socketDataAsString, Employee.class); 
+3
source

If you must directly use low-level sockets, you can do several ways. You can convert it to text format and send bytes, and then restore it from the other side. If your objects are serializable, you can send them by socket (http://www.rgagnon.com/javadetails/java-0043.html).

If you have some flexibility, you can use RMI for remote communication as well.

0
source

Source: https://habr.com/ru/post/1397916/


All Articles