Java中服务器断开连接

发布于 2024-07-16 02:44:16 字数 443 浏览 7 评论 0原文

相关帖子没有回答我的问题。

我有一个服务器,它执行以下操作:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

始终不够 2024-07-23 02:44:16

不要使用 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.

み零 2024-07-23 02:44:16

如果这是使用套接字完成的,您可能需要检查 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文