必须服务器和客户端具有声明ObjectOutputStream&的反向序列。 ObjectInputStream的? [英] Must server & client have reverse sequence of claiming ObjectOutputStream & ObjectInputStream?

查看:106
本文介绍了必须服务器和客户端具有声明ObjectOutputStream&的反向序列。 ObjectInputStream的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的实验中,

如果服务器具有此功能:

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.

这是什么原因?是否有正式的API规范?

What's the reason for this? and is there a formal API spec for it?

推荐答案

是的。我知道这可能会发生。 ObjectInputStream 构造函数说:

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


创建从指定的 InputStream 读取的 ObjectInputStream 。从流中读取序列化流头并进行验证。此构造函数将阻止,直到相应的 ObjectOutputStream 已写入并刷新标题。

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

因此,如果客户端和服务器在 ObjectOutputStream 之前构造了他们的 ObjectInputStream ,那么两者都将阻止等待发送序列化流标题的另一端。

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.

请注意,这发生在对象流级别,而不是套接字或字节流级别。如果您通过套接字执行简单的字节或字符或数据I / O,则无需担心流的构造顺序。

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

这篇关于必须服务器和客户端具有声明ObjectOutputStream&的反向序列。 ObjectInputStream的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆