ObjectInputStream constructor hangs program

我的未来我决定 提交于 2019-12-12 06:45:44

问题


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");

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.


回答1:


Everything tells me to declare the objectInputStream before the ObjectInputStream.

No it doesn't, it tells you to construct the ObjectOutputStream before the ObjectInputStream, and you're doing that.

Other places tell me to flush the Object input stream.

No, they tell you to flush the ObjectOutputStream, and you're doing that too.

Do read accurately.

This code just hangs the program and waits waiting for the so-called header.

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.

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.



来源:https://stackoverflow.com/questions/47425967/objectinputstream-constructor-hangs-program

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