When a client disconnects using CTRL-C or the connection is terminated the server should produce a message stating that it has done so rather then producing an exception as follows:
Exception in thread “Thread-1” java.lang.NullPointerException
at ChatServerThread.handleClient(ChatServerThread.java:31)
at ChatServerThread.run(ChatServerThread.java:17)
It began exhbiting this behavior after I converted from read/writeUTF() to readLine() and writeByte() respectively, and having the server respond to the client with what the client sent. See Exception in thread for details.
Question is how to get the EOFException to functionality to work again so that Client closed the connection. is printed verse the exception message. Line 31 is 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();
}
}
The exception is thrown from the second line:
Obviously the
nextCommandisnull.streamInis aBufferedReader, quoting JavaDoc ofreadLine():This is a different behaviour when compared to
DataInputStream.readUTF():My guess is that Ctrl + C interrupts blocking
readLine()and signalling end of stream.