Passing TreeMap object over Socket (from server to client)

272 Views Asked by At

Is it possible to send a TreeMap (containing keys and values) over a socket from server to client?

2

There are 2 best solutions below

5
On BEST ANSWER

Writing to a socket is no different than writing to a file. The ObjectOutputStream class abstracts that layer for us. So you can test that your Serialization is working smoothly with file IO; then it is very easy to write to a Socket.

First Step: Test Your Serialization

TreeMap<YourKeyClass, YourValueClass> treeMap = 
             new TreeMap<>();
buildMyTree(treeMap);
FileOutputStream fout = new FileOutputStream("path/to/your/file.ser");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(treeMap);

Second Step: Test Your Deserialization

Read your object back to check deserialization:

FileInputStream fin = new FileInputStream("path/to/your/file.ser");
ObjectInputStream ois = new ObjectInputStream(fin);
TreeMap<YourKeyClass, YourValueClass> treeMapFromFile = ois.readObject();

TreeMap is Serializable. Everything runs perfectly fine, as long as YourValueClass does not have complex structure that hinders serialization. For instance you may have recursive references to other objects in your YourValueClass, in which case you have to work on your work on your own writeObject and readObject implementations for Serialization.

So a read and write check is very important to be sure everything runs according to your structure.

Third Step: Move to Socket Programming

Once you are sure your serialization is working, move to socket programming. It is very important that you're confident that your serialization is working perfectly, before moving on to the socket, since if you miss a point on serialization then if anything fails during socket implementation, it will be very hard to find where the problem is.

Server Side:

//initialize your socket 
//start listening on your socket
TreeMap<YourKeyClass, YourValueClass> treeMap = new TreeMap<>();
buildMyTree(treeMap);
ObjectOutputStream oos = new ObjectOutputStream(socketToClient.getOutputStream());
oos.writeObject(treeMap);

Client Side:

//initialize your socket 
ObjectInputStream ios = new ObjectInputStream(socketToServer.getInputStream());
TreeMap<YourKeyClass, YourValueClass> treeMapFromSocket = ois.readObject();

You can use refer to the following sources:

2
On

Yes, it's possible.

java.util.TreeMap implements interface java.io.Serializable. Also all of keys and values int TreeMap must implements this interface.