【发布时间】:2012-03-19 10:11:28
【问题描述】:
当客户端使用 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();
}
}
【问题讨论】:
-
第 31 行是哪一行?这与我对你上一个问题的反馈相同。请帮助我们。
-
问题是如何让 EOFException 功能再次工作,以便 客户端关闭连接。 打印出异常消息。 31号线
if( nextCommand.equals(".bye") ) {
标签: java multithreading exception exception-handling io