I have a Java Server/Client application that allows client input until disconnection, using a while loop. This is done inside a ClientHandler class object that extends Thread and uses the run() method, so each connected client is being communicated with on it's own Thread.
This is what happens so far:
public void run()
{
//receive and respond to client input
try
{
//strings to handle input from user
String received, code, message;
//get current system date and time
//to be checked against item deadlines
Calendar now = Calendar.getInstance();
//get initial input from client
received = input.nextLine();
//as long as last item deadline has not been reached
while (now.before(getLastDeadline()))
{
//////////////////////////////////
///processing of client message///
//////////////////////////////////
//reload current system time and repeat loop
now = Calendar.getInstance();
//get next input from connected client
received = input.nextLine();
//run loop again
}
}
//client disconnects with no further input
//no more input detected
catch (NoSuchElementException nseEx)
{
//output to server console
System.out.println("Connection to bidder has been lost!");
//no system exit, still allow new client connection
}
}
This all works fine, and the NoSuchElementException is handled when a client stops running their program (as there will be no subsequent input).
What I want to do is detect when a client Socket is disconnected from the server, so the server can update a display of currently connected clients. I have been told to do this by catching SocketException, and I have read up on this exception but am still a bit confused by how I would have to implement it.
From what I understand (although I could be wrong), a SocketException has to be caught on the client-side. Is this correct? If this is the case, can the SocketException run in harmony with the NoSuchElementException that I already have in place, or will that exception have to be removed/replaced?
A basic example of how to incorporate catching a SocketException would be a massive help, as I've not been able to find any relevant examples online.
Thanks,
Mark