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

徘徊边缘 提交于 2019-12-17 21:28:57

问题


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



来源:https://stackoverflow.com/questions/14639003/must-server-client-have-reverse-sequence-of-claiming-objectoutputstream-obje

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!