Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java socket server, client detect server has died

Tags:

java

sockets

If I kill the Socket Server process, my Socket client process does not receive any errors, it continues to loop forever on the following code:

public void run() {
    while(readData) {
      String inputLine = null;
      try {
        while((inputLine = m_inputStream.readLine()) != null) {
          //do stuff
        }
      } catch (IOException e) {
         readData = false;
     }
  }
}

How can I detect that the socket server is gone and terminate the loop?

like image 942
anio Avatar asked Apr 28 '26 05:04

anio


1 Answers

Terminate the outer loop when the call to readLine() returns null.

No exception is thrown when the server closes the connection normally. The stream should return null to signal the end of data.

This can be done with a loop like this:

public void run() {
  try {
    while (true) {
      String line = input.readLine();
      if (line == null)
        break;
      /* Process line. */
      ...
    }
  } catch (IOException ex) {
    /* Handle the exception as desired. */
    ex.printStackTrace();
  }
}
like image 183
erickson Avatar answered Apr 29 '26 20:04

erickson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!