客户端断开时线程中的异常

时间:2012-02-29 21:59:37

标签: java multithreading exception exception-handling io

当客户端使用CTRL-C断开连接或连接终止时,服务器应该生成一条消息,说明它已经这样做,而不是产生如下的异常:

  

线程“Thread-1”中的异常java.lang.NullPointerException           在ChatServerThread.handleClient(ChatServerThread.java:31)           在ChatServerThread.run(ChatServerThread.java:17)

在我分别从read / writeUTF()转换为readLine()和writeByte()并让服务器用客户端发送的内容响应客户端之后,它开始讨论这种行为。有关详细信息,请参阅Exception in thread

问题是如何使EOFException功能再次运行,以便客户端关闭连接。打印异常消息。第31行是if( nextCommand.equals(".bye") ) {

import java.net.*;
import java.io.*;

//public class ChatServerThread implements Runnable
public class ChatServerThread extends Thread
{  private Socket          socket   = null;
   private ChatServer      server   = null;
   private int             ID       = -1;
   private BufferedReader streamIn =  null;
   private DataOutputStream streamOut = null;

   public ChatServerThread(ChatServer _server, Socket _socket)
   {  server = _server;  socket = _socket;  ID = socket.getPort();
   }
   public void run() {
   try {
       handleClient();
   } catch( EOFException eof ) { \\This does not seem to be working now and it previously was
        System.out.println("Client closed the connection.");
   } catch( IOException ioe ) {
        ioe.printStackTrace();
   }
}

   public void handleClient() throws IOException {
      boolean done = false;
      try {
      System.out.println("Server Thread " + ID + " running.");
      while (!done) {
        String nextCommand = streamIn.readLine();
        if( nextCommand.equals(".bye") ) {
           System.out.println("Client disconnected with bye.");
           done = true;
        } else {
           System.out.println( nextCommand );
           String nextReply = "You sent me: " + nextCommand.toUpperCase() + '\n';
           streamOut.writeBytes ( nextReply );
        }
     }
   } finally {
     streamIn.close();
     streamOut.close();
     socket.close();
   }
   }
   public void open() throws IOException
   {
      streamIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      streamOut = new DataOutputStream(socket.getOutputStream());
   }
   public void close() throws IOException
   {  if (socket != null)    socket.close();
      if (streamIn != null)  streamIn.close();
      if (streamOut != null) streamOut.close();
   }
}

1 个答案:

答案 0 :(得分:2)

从第二行抛出异常:

String nextCommand = streamIn.readLine();
if( nextCommand.equals(".bye") ) {

显然nextCommandnullstreamInBufferedReader,引用了readLine()的JavaDoc:

  

返回:

     

包含该行内容的字符串,不包括任何行终止字符,如果已到达流末尾,则为null

DataInputStream.readUTF()相比,这是一种不同的行为:

  

返回:

     

Unicode字符串。

     

抛出:

     

EOFException - 如果此输入流在读取所有字节之前到达结尾。

我的猜测是 Ctrl + C 中断阻塞readLine()和信号流结束。