套接字关闭不抛出IOException

问题描述:

我正在写一个基本的服务器客户端程序在Java中,我试图处理客户端意外终止的情况。套接字关闭不抛出IOException

public void run() { 
    while(alive) { 
     try { 
      // socketIn is a BufferedReader wrapped around the socket's InputStream. 
      String input = socketIn.readLine(); 
      if(input == null) 
       continue; 
      String response = processInput(input); 
      // socketOut is a PrintWriter wrapped around the socket's OutputStream. 
      if(response != null) { 
       socketOut.println(response); 
       socketOut.flush(); 
      } 
     } catch(IOException e) { 
      System.out.println("TRACE 1"); 
      alive = false; 
     } 
    } 
    System.out.println("TRACE 2"); 
} 

但是,当我杀死客户端,循环继续进行,没有TRACE打印出来。我假设当一个套接字从另一端关闭,我试图从它读取,它会抛出一个IOException。

这是一个糟糕的假设吗?我能做些什么来解决这个问题?

+1

考虑使用连接超时,并且注意SocketExceptions。 – Zaki

+0

连接超时是一个好主意,我认为SocketException是IOException的一个子类。 – DanielGibbs

readLine()将在数据流结束时返回null,这是远程端正常关闭连接时发生的情况。你正试图在这种情况下continue,这将永远循环。如果连接异常中断,将会抛出IOException

+0

我们通常从远程套接字读取如下:String msg = null; while((msg = s.readLine())!= null){//做msg读取的内容...} //从远程端关闭套接字。 –