Java socket server, client discovery server

If I kill the Socket Server process, my client Socket process will not receive any errors, it will continue the cycle forever according to 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 missing and terminating the loop?

+3
source share
2 answers

End the outer loop when the call readLine()returns null.

No exception occurs when the server normally closes the connection. The stream should return nullto signal completion of data.

This can be done using a loop:

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();
  }
}
+4
source

erickson , ? (, sun.net.client.defaultReadTimeout). , , , , , .

0

Source: https://habr.com/ru/post/1713104/


All Articles