中断插座连接

时间:2012-12-01 17:48:29

标签: java sockets

我有一个套接字程序,它通过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();
}

2 个答案:

答案 0 :(得分:2)

我认为您的问题是PrintWriter。见its documentation

  

此类中的方法永远不会抛出I / O异常,尽管它有些异常   施工人员可以。客户可以询问是否有任何错误   通过调用checkError()发生。

改为使用BufferedWriter

请注意,java.util.Scanner具有相同的问题(如果您在服务器端使用它)

答案 1 :(得分:1)

我刚检查过,PrintWriter.checkError()方法帮助了解了我的问题。当客户端断开连接时,方法返回true。如上所述:Flushes the stream if it's not closed and checks its error state.

// Server
this.out = new PrintWriter(sock.getOutputStream());
while (true) {
   this.out.write("Hello");
   this.out.flush();
   if(this.out.checkError()){
      //...
   }
}