Java中服务器断开连接
相关帖子没有回答我的问题。
我有一个服务器,它执行以下操作:
EVERY TWO SECONDS DO:
if the inputstream is not null {
if inputStream.available() is 0
{
return
}
print "handling input stream"
handleTheInputStream();
}
即使在我的客户端断开连接后,服务器也不会通过 IOException 识别它。 另一篇文章说我会看到一个 End-of-Stream 角色。 然而,情况并非如此,因为在我的客户端断开连接后,我从未看到“处理输入流”,这表明没有可用的数据。
也许我目前理解其工作原理的方式有问题。
请帮忙。
Related posts didn't answer my question.
I have a server which does something like:
EVERY TWO SECONDS DO:
if the inputstream is not null {
if inputStream.available() is 0
{
return
}
print "handling input stream"
handleTheInputStream();
}
Even after my client disconnects, the server doesn't recognize it through an IOException. The other post said that I would see an End-of-Stream character. However, that is not the case, since after my client disconnects I never see "handling input stream" which indicates that no data is available.
Perhaps something is wrong with the way I currently understand how this works.
Please help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要使用
available()
- 它表示当前是否有可用数据,而不是将来是否有可用数据。 换句话说,它是错误的检测断开连接的工具。基本上你应该调用
read()
(并处理数据)直到它返回-1,此时意味着客户端已断开连接。Don't use
available()
- that says whether or not there's currently data available, not whether there will be data available in the future. In other words, it's the wrong tool to use to detect disconnection.Basically you should call
read()
(and process the data) until it returns -1, at which point it means the client has disconnected.如果这是使用套接字完成的,您可能需要检查 Socket 类的各种实例方法,如 isClosed() 或 isInputShutdown()。
当然,这假设操作该流的方法可以访问 Socket 对象而不仅仅是 InputStream。
If this is done using sockets, you may want to check the Socket class's various instance methods, such as isClosed() or isInputShutdown().
Of course, this assumes that the method operating on this stream has access to the Socket object and not just the InputStream.