views:

46

answers:

2

Today I've got an problem with an ObjectStream (Input and also Output). I used the Input and OutputStream which came directly out of the socket.

While initialising the streams my runs and runs and runs. With no error message. I got no error message. It seems that the constructor of the ObjectInputStream runs endless...

Here is the code where the problem exists. socket.isConnected was true.

ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());

Any ideas?

A: 

The object input stream reads the header sent by the object output stream which is it constructed. If you haven't sent the header, it will wait forever.

The simple solution is to ALWAYS create the object output stream first and flush it before creating the object input stream.

Peter Lawrey
thank you, i'll try this solution!
Moritz
A: 

I found this

Create ObjectOutputStream Before ObjectInputStream If you are writing code that transmits data bidirectionally using ObjectInputStream and ObjectOutputStream, be careful to construct the ObjectOutputStream first.

If you instead construct the ObjectInputStream first, both ends will block and eventually fail in the constructor. This is because the input stream constructor waits for an initial string of bytes to arrive from the ObjectOutputStream open(). In the unidirectional case, where one side is writing and the other is reading, everything goes smoothly. However in the bidirectional case, if both sides attempt to construct the input stream first, both are waiting for the other to construct the output stream, and neither can proceed.

If your exception handling allows communications to proceed after constructing the input stream fails, then the symptoms of this problem are that both sides block for a period of time, one gets the exception and proceeds to construct the ObjectOutputStream. The other end then is able to construct its ObjectInputStream, since the initialization sequence just arrived.

Fortunately the fix is straightforward. Move the creation of the ObjectOutputStream before that of the ObjectInputStream. Then each end will transmit the initialization sequence before trying to open its input stream. The initialization sequence is ready and waiting, so the construction of the input stream goes normally, and object transfers can then commence without any delay.

Moritz