0

In a client/server setup, I'm meant to be able to detect if a client disconnects, and remove the client from the list of clients on the server. I can do this in all instances, except for if the server is waiting for an input from the client.

For example, the client terminates the process, when the server is on this part of its loop:

int target = Integer.parseInt(Scanner.next())

For writing, I have that solved. Using the PrintWriter's checkError method, I can tell if there has been an issue writing to the client, and thus kill the connection since the client has disconnected. Is there a similar option for using the scanner, or an alternative class that has this functionality which I can use?

jario5615
  • 1
  • 1

1 Answers1

0

So, Scanner.next() will block the execution of the program, so I would reccomend first checking wether the scanner has anything to read with the method Scanner.hasNext() (https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html)

something like this is clumsy but I think it could work:

while(clientIsConnected){
   if(scanner.hasNext()){
      int myInt = Scanner.nextInt();
      doSomething(myInt);
   }
   Thread.sleep(1000);
}

I would also recommend using DataInput and DataOutput Streams (https://www.tutorialspoint.com/java/java_networking.htm), I think they are a better alternative to your Scanner. If you could provide us with your code I could help you in determining if a client connection is closed.

With DataInputStreams when the client disconnects, it reads a -1 so you would know the client is dead (Detect DataInputStream end of stream)

panosjuan
  • 49
  • 2
  • 7