在我的实验中,
如果服务器有这个:
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
然后客户端必须以相反的顺序执行此操作:
ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
否则服务器和客户端会死锁。
这是什么原因?是否有正式的 API 规范?
最佳答案
是的。我知道这怎么可能发生。 ObjectInputStream
的 javadoc构造函数这样说:
"Creates an
ObjectInputStream
that reads from the specifiedInputStream
. A serialization stream header is read from the stream and verified. This constructor will block until the correspondingObjectOutputStream
has written and flushed the header."
因此,如果客户端和服务器都在构造它们的ObjectInputStream
之前构造它们的ObjectInputStream
,那么它们都将阻塞等待另一端发送序列化流 header 。
请注意,这是在对象流级别发生的,而不是套接字或字节流级别。如果您通过套接字执行简单的字节或字符或“数据”I/O,则无需担心流的构造顺序。
也不是,如果您在客户端和服务器端(两者)都有单独的线程来进行读取和写入,那么这不是问题。在所有条件都相同的情况下,这可能是一个更好的架构,因为它允许客户端/服务器通过套接字进行“全双工”通信。
关于java - 服务端和客户端必须有相反的声明 ObjectOutputStream 和 ObjectInputStream 的顺序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14639003/