In my experiment,
if Server has this:
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
then client side has to do this, in the opposite order:
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
Otherwise server and client will deadlock.
What's the reason for this? and is there a formal API spec for it?
Yes. I see how this might happen. The javadoc for the
ObjectInputStream
constructor says this:So if both the client and the server construct their
ObjectInputStream
before theirObjectOutputStream
, then both will block waiting for the other end to send the serialization stream header.Note that this is happening at the object stream level, not the socket or bytestream levels. If you are doing simple byte or character or "data" I/O over a socket, you don't need to worry about the order in which the streams are constructed.
Also not, that this is not a problem if you have separate threads on (both) the client and server sides to do the reading and writing. All things being equal, that is probably a better architecture because it allows the client/server communication over the socket to be "full duplex".