且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

新的 ObjectInputStream() 块

更新时间:2023-11-30 14:25:46

您需要在连接两端的 ObjectInputStream 之前创建 ObjectOutputStream(!).在创建 ObjectInputStream 时,它会尝试从 InputStream 读取对象流标头.因此,如果另一端的 ObjectOutputStream 尚未创建,则没有要读取的对象流标头,它将无限期阻塞.

You need to create the ObjectOutputStream before the ObjectInputStream at both sides of the connection(!). When the ObjectInputStream is created, it tries to read the object stream header from the InputStream. So if the ObjectOutputStream on the other side hasn't been created yet there is no object stream header to read, and it will block indefinitely.

或者换种说法:如果双方先构造ObjectInputStream,双方都会阻塞试图读取对象流头,直到ObjectOutputStream已创建(在线的另一侧);这永远不会发生,因为双方都在 ObjectInputStream 的构造函数中被阻塞了.

Or phrased differently: If both sides first construct the ObjectInputStream, both will block trying to read the object stream header, which won't be written until the ObjectOutputStream has been created (on the other side of the line); which will never happen because both sides are blocked in the constructor of ObjectInputStream.

这可以从ObjectInputStream(InputStream in):

从流中读取并验证序列化流标头.此构造函数将阻塞,直到相应的 ObjectOutputStream 已写入并刷新标头.

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.

这也在 Esmond Pitt 的 Java 基础网络 的第 3.6.2 节中进行了描述.

This is also described in section 3.6.2 of Fundamental networking in Java by Esmond Pitt.