ObjectInputStream构造函数挂起程序 [英] ObjectInputStream constructor hangs program

查看:154
本文介绍了ObjectInputStream构造函数挂起程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尽力解决此问题.

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之前声明objectInputStream.

Everything tells me to declare the objectInputStream before the ObjectInputStream.

不,不是,它告诉您在ObjectInputStream之前构造ObjectOutputStream,而您正在这样做.

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.

不,他们告诉您刷新ObjectOutputStream,您也正在这样做.

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

请准确阅读.

此代码只是挂起程序并等待等待所谓的标头.

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

那是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构造函数挂起程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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