Python中文网

一个关于 编程问题的解答网站.

有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

客户端断开连接时线程中出现java异常

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

Exception in thread "Thread-1" java.lang.NullPointerException at ChatServerThread.handleClient(ChatServerThread.java:31) at ChatServerThread.run(ChatServerThread.java:17)

在我分别从read/writeUTF()转换为readLine()和writeByte()并让服务器用客户端发送的内容响应客户端之后,它开始发现这种行为。详见Exception in thread

问题是如何让EOFEException to功能重新工作,以便客户端关闭连接打印在异常消息中。第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) 个答案

  1. # 1 楼答案

    从第二行引发异常:

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

    显然nextCommandnullstreamIn是一个^{},引用了^{}的JavaDoc:

    Returns:

    A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

    ^{}相比,这是一种不同的行为:

    Returns:

    a Unicode string.

    Throws:

    EOFException - if this input stream reaches the end before reading all the bytes.

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