JAVA:处理插座断开连接 [英] JAVA : Handling socket disconnection

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

问题描述


  1. 两台计算机通过套接字连接进行连接。如果服务器/客户端从它们的末尾关闭连接
    (即关闭 InputStream OutputStream 套接字)那么如何告知
    另一端是否断线?我知道有一种方法 - 尝试读取 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()抛出 EOFException ,对于任何其他X.

  • read() returns -1
  • readLine() returns null
  • readXXX() throws EOFException, for any other X.

As 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天全站免登陆