我有一个套接字程序,它通过 PrintWriter(out.write(String str)) 发送文本数据,另一端 BufferedReader(in.readLine()) 正在接收此数据。
如果其中一个客户端断开连接,我想通过某种“超时”来保护我的程序,但我对其进行了测试,在工作期间,当客户端关闭时,服务器仍在发送数据,并且没有中断,也没有套接字关闭。
对于客户端来说也是如此,我想中断连接并显示信息,例如“服务器不工作”。 我该如何处理这个问题?
// Server
out = new PrintWriter( sock.getOutputStream());
while( true ) {
this.out.write("Hello");
this.out.flush();
}
// Client
in = new BufferedReader( new InputStreamReader( sock.getInputStream()));
while (true) {
in.readLine();
}
最佳答案
我认为你的问题是PrintWriter。请参阅its documentation :
Methods in this class never throw I/O exceptions, although some of its constructors may. The client may inquire as to whether any errors have occurred by invoking checkError().
使用BufferedWriter相反。
请注意,java.util.Scanner 也有同样的问题(如果您在服务器端使用它)
关于java - 中断套接字连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13662006/