我创建了一个接受TCP连接的服务器。连接到套接字后,它循环以从输入流中读取数据。
步骤:
现在我正在关闭客户。
然后Server给我SocketException连接重置
在从输入流中读取之前,如何检查我的客户端是否处于活动状态。
答案 0 :(得分:2)
如果您的服务器获得“连接重置”,则可能是写入已被另一端关闭的连接。用户按下“后退”按钮的浏览器就是一个很好的例子。如果这是预期的条件,请忽略该异常。如果它构成应用程序协议错误,请调试应用程序。
答案 1 :(得分:-1)
有两种方法可以检查套接字是否已连接,您可以读取或写入它,如果已连接,您将不会收到错误,如果没有连接,您将收到错误。这是我检查套接字是否连接的方式:
BufferedReader reader;
public void run()
{
try
{
String message;
while((message = reader.readLine())!=null) //The thread stops here untill the reader has somthing to read
{
System.out.println(message);
}
}catch(Exception e)
{
System.out.println("Client disconnected!");
// an error is thrown when reader cannot read the stream because it is closed, you will get a connection reset error.
}
}
当连接套接字时,阅读器会等待,直到有一些东西需要读取(message = reader.readLine())。当客户端断开连接并且Socket关闭时,阅读器会抛出异常,因为没有任何内容可以被读取,因为流已关闭。我希望这有帮助!