JAVA:处理套接字断开连接 [英] JAVA : Handling socket disconnection

查看:44
本文介绍了JAVA:处理套接字断开连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 两台计算机通过套接字连接进行连接.如果服务器/客户端关闭连接从他们的末端(即关闭 InputStreamOutputStreamSocket)然后我如何通知另一端关于断开连接?我知道有一种方法 - 尝试从 InputStream 中读取,如果连接关闭,它会抛出 IOException,但有没有其他方法可以检测到这种情况?
  2. 另一个问题,我在网上查了一下问题,看到了inputStream.available()不能解决这个问题.这是为什么?
  1. Two computers are connected by socket connection. If the server/client closes the connection from their end(i.e closes the InputStream, OutputStream and Socket) then how can I inform the other end about the disconnection? There is one way I know of - trying to read from the InputStream, which throws an IOException if connection is closed, but is there any other way to detect this?
  2. Another question, I looked the problem up on the internet and saw inputStream.available() does not solve this problem. Why is that?

附加信息:我要求另一种方式,因为如果我必须尝试从InputStrem 检测断开连接.

Additional Information : I'm asking for another way because my project becomes tough to handle if I have to try to read from the InputStrem to detect a disconnection.

推荐答案

试图从 InputStream 中读取,这会引发 IOException

trying to read from the InputStream, which throws an IOException

这是不对的.如果对等方关闭套接字:

That is not correct. If the peer closes the socket:

  • read() 返回 -1
  • readLine() 返回 null
  • readXXX() 为任何其他 X 抛出 EOFException.
  • read() returns -1
  • readLine() returns null
  • readXXX() throws EOFException, for any other X.

由于 InputStream 只有 read() 方法,所以它只返回 -1:它不会在 EOS 上抛出 IOException.

As InputStream only has read() methods, it only returns -1: it doesn't throw an IOException at EOS.

与此处的其他答案相反,没有 TCP API 或 Socket 方法会告诉您对等方是否已关闭连接.您必须尝试读取或写入.

Contrary to other answers here, there is no TCP API or Socket method that will tell you whether the peer has closed the connection. You have to try a read or a write.

您应该使用读取超时.

InputStream.available() 不能解决问题,因为它不返回任何类型的 EOS 指示.它的正确用法很少,这不是其中之一.

InputStream.available() doesn't solve the problem because it doesn't return an EOS indication of any kind. There are few correct uses of it, and this isn't one of them.

这篇关于JAVA:处理套接字断开连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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