Andre's Blog

20160626 Sending Objects Via Sockets In Java

[JAVA] [CISYSTEM] [SOCKET]

For my software project I have to implement a communication between different PCs.

I have decided :

  1. I want to communicate via sockets.
  2. I want to communicate using objects.

I like socket communication, because synchronization via files depends on the implementation of the filesystem used for the sharedrive and I guess it is faster using sockets.

I like objects, because they help me passing packets of information and that means I don't need to implement my own language based on strings to do so. Communicating only via strings would increase the complexity of the program and decrease its performance. It would also mean to reinvent again what objects already are : containers for information.

FYI: If you suffer from maintaining software which has its own string-based language to pass information instead of using objects you may be interested in these blog articles of my friend Eike :

Kikentai Management : Dead horses: 5 reasons to ride
Kikentai Management : Not invented here

When I started implementing my socket connection everything was fine. I had started with sending strings to check the communication itself and then I switched over to sending objects.

To cut the long story short : It did not work, only my first object was passed, but the others were not send. After playing around for some time I even had the case that I received the same object again and again.

I have found out that I was dealing with these problems :

  1. You have to flush your ObjectOutputStream after sending the object.
  2. Objects which have been send will not be send again, even if their content changes.

I have not spend time yet on finding out when to flush a stream, but I will do as soon as I notice a performance problem here. Till then I just accept I have to flush the stream.

For handling the objects you have 2 options :

  1. You can create a new object every time you send an object.
  2. You can tell Java to write the object unshared to the stream which means, write the object in any case, even if this would not send any new content.

As long as I will always update all members of my object before sending it I feel its a good idea to reuse the same object again.

Here I show you some code-snippets of how I did it :

Sending Objects Via Sockets

This is the complete example code including my build.gradle script : zipped example of Sending Objects Via Sockets

Select where to go ...


The Blog
My Technical Blogs
Projects
Blogs Of Friends
RSS
CV/About
Me