I am trying to deal with client disconnects in a simple java application that sends chat messages using a client and a server.
Here’s the problem
public void run() {
try {
System.out.println("Client Connected");
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
theServer.handle(inputLine, this);
}
out.close();
in.close();
socket.close();
System.out.println("Client Disconnected");
} catch (Exception e) {
e.printStackTrace();
}
}
With this code here, it runs the while loop while the input line is not null. If it is null then it will stop looping and close the in and out streams as well as the socket. Now, this is all working fine apart from the output in the console is this:
Client Connected
null
Client(/127.0.0.1): null
null
Client(/127.0.0.1): null
null
Client(/127.0.0.1): null
null
Client(/127.0.0.1): null
Client Disconnected
I can’t figure out why the loop would keep looping even when the input is null!! It seems to take a while to realise that it’s null before exiting the loop. I need it to exit straight away without a delay.
Any help would be appreciated,
shadrxninga
The only explanations that I can think of are:
in.readLine()is returning the string"null"(possibly with trailing whitespace),inrefers to some custom stream or reader wrapper whosereadLine()method is doing something weird, orYou say:
This is a “voodoo programming” explanation. It cannot possibly be correct unless there’s a bug in your Java implementation. And that is extremely unlikely.