WMR*_*WMR 63
该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());
}
}
Run Code Online (Sandbox Code Playgroud)
启动服务器,启动客户端.您将看到它打印"connected:true"两次,即使套接字第二次关闭.
真正找到的唯一方法是通过读取(你将得到-1作为返回值)或IOException在相关的Input/OutputStreams上写入(一个(破坏的管道)).
Tho*_*ues 26
由于答案有所不同,我决定对此进行测试并发布结果 - 包括测试示例.
这里的服务器只是将数据写入客户端,并且不期望任何输入.
服务器:
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 ...
}
Run Code Online (Sandbox Code Playgroud)
小智 13
您还可以在写入客户端套接字时检查套接字输出流错误.
out.println(output);
if(out.checkError())
{
throw new Exception("Error transmitting data.");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
137708 次 |
| 最近记录: |