Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

java - Must server & client have reverse sequence of claiming ObjectOutputStream & ObjectInputStream?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...