如何检测远程套接字上是否已调用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());
}
}
启动服务器,启动客户端。你会看到它打印了 "connected: 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 ...
}
在向客户端套接字写入数据时,您还可以检查套接字输出流的错误。
out.println(output);
if(out.checkError())
{
throw new Exception("Error transmitting data.");
}
如果远程系统已断开/关闭连接,则方法Socket.Available将立即抛出SocketException。