如何检测远端插座关闭?
2022-08-31 11:39:02
如何检测是否已在远程端的套接字上被调用?Socket#close()
该方法无济于事,即使远程端已关闭套接字,它也会返回。试试这个:isConnected
true
public class MyServer {
public static final int PORT = 12345;
public static void main(String[] args) throws IOException, InterruptedException {
ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(PORT);
Socket s = ss.accept();
Thread.sleep(5000);
ss.close();
s.close();
}
}
public class MyClient {
public static void main(String[] args) throws IOException, InterruptedException {
Socket s = SocketFactory.getDefault().createSocket("localhost", MyServer.PORT);
System.out.println(" connected: " + s.isConnected());
Thread.sleep(10000);
System.out.println(" connected: " + s.isConnected());
}
}
启动服务器,启动客户端。您将看到它打印了两次“已连接:true”,即使插槽第二次关闭也是如此。
真正找出答案的唯一方法是在关联的输入/输出流上读取(您将获得-1作为返回值)或写入(将抛出(将抛出损坏的管道)。IOException
由于答案偏离,我决定对此进行测试并发布结果 - 包括测试示例。
这里的服务器只是将数据写入客户端,不需要任何输入。
服务器:
ServerSocket serverSocket = new ServerSocket(4444);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
while (true) {
out.println("output");
if (out.checkError()) System.out.println("ERROR writing data to socket !!!");
System.out.println(clientSocket.isConnected());
System.out.println(clientSocket.getInputStream().read());
// thread sleep ...
// break condition , close sockets and the like ...
}