3 回答

TA贡献1770条经验 获得超3个赞
该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”,即使套接字第二次关闭也是如此。
真正找出答案的唯一方法是IOException对关联的Input / OutputStream 进行读取(您将获得-1作为返回值)或写入(将抛出(破损的管道))。

TA贡献1877条经验 获得超6个赞
您还可以在写入客户端套接字时检查套接字输出流错误。
out.println(output);
if(out.checkError())
{
throw new Exception("Error transmitting data.");
}
添加回答
举报