JAVA:处理插座断开连接 [英] JAVA : Handling socket disconnection
问题描述
- 两台计算机通过套接字连接进行连接。如果服务器/客户端从它们的末尾关闭连接
(即关闭InputStream
,OutputStream
和套接字
)那么如何告知
另一端是否断线?我知道有一种方法 - 尝试读取InputStream
,
抛出IOException
如果连接已关闭,但有没有其他方法可以检测到这一点? - 另一个问题,我在互联网上看了问题并看到
inputStream.available()
无法解决此问题。这是为什么?
- Two computers are connected by socket connection. If the server/client closes the connection
from their end(i.e closes the
InputStream
,OutputStream
andSocket
) then how can I inform the other end about the disconnection? There is one way I know of - trying to read from theInputStream
, which throws anIOException
if connection is closed, but is there any other way to detect this? - 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 -1readLine()
returns nullreadXXX()
throwsEOFException
, 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屋!