问题描述
我已经尽力解决此问题.
I have tried every solution I can find to this problem.
server = new ServerSocket(9421);
client = new Socket("localhost", 9421);
out = new ObjectOutputStream(client.getOutputStream());
out.flush();
System.out.println("Starting input streams");
in = new ObjectInputStream(client.getInputStream());
System.out.println("input streams are now running");
所有内容都告诉我在ObjectInputStream之前声明objectInputStream.其他地方告诉我刷新对象输出流.这段代码只是将程序挂起,并等待所谓的标头.
Everything tells me to declare the objectInputStream before the ObjectInputStream. Other places tell me to flush the Object output stream. This code just hangs the program and waits waiting for the so-called header.
推荐答案
不,不是,它告诉您在ObjectInputStream
之前构造ObjectOutputStream
,而您正在这样做.
No it doesn't, it tells you to construct the ObjectOutputStream
before the ObjectInputStream
, and you're doing that.
不,他们告诉您刷新ObjectOutputStream
,您也正在这样做.
No, they tell you to flush the ObjectOutputStream
, and you're doing that too.
请准确阅读.
那是100%正确的.没有什么所谓的.头没有写.对等方尚未构建其ObjectOutputStream
,并且该代码将阻塞,直到它断开,断开连接或网络中断为止.
That is exactly 100% correct. There is nothing 'so-called' about it. And nothing has written the header. The peer hasn't constructed its ObjectOutputStream
yet, and this code will block until it does, or disconnects, or the network drops out.
实际上,对等端甚至没有接受连接.您不能在同一线程中运行所有这些代码. ServerSocket
需要一个单独的accept-loop线程,并且该线程需要为每个接受的套接字启动另一个线程,以相同的顺序构造对象流.
In fact the peer hasn't even accepted the connection. You can't run all this code in the same thread. The ServerSocket
needs a separate accept-loop thread, and that thread needs to start a further thread per accepted socket that constructs the object streams in the same order.
这篇关于ObjectInputStream构造函数挂起程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!