Must server & client have reverse sequence of clai

2019-01-19 09:12发布

问题:

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?

回答1:

Yes. I see how this might happen. The javadoc for the ObjectInputStream constructor says this:

"Creates an ObjectInputStream that reads from the specified InputStream. A serialization stream header is read from the stream and verified. This constructor will block until the corresponding ObjectOutputStream has written and flushed the header."

So if both the client and the server construct their ObjectInputStream before their ObjectOutputStream, 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".