1

From (Java Network Programming fourth edition): To tell if a socket is currently open, you need to check that isConnected() returns true and isClosed() returns false. For an example:

boolean connected = socket.isConnected() && ! socket.isClosed();

I need to find a way to discover as soon as possible that the client has disconnected from the Server Socket. Using the trick described above,I have tried the following :

    Socket socket = ...;
    while (socket.isConnected() && !socket.isClosed()) {
      // do something ...
      // here, the client is always connected   
     }
    // client is disconnected 

The above approach works for me, but it is always correct?. it detects all the cases?

Mosam Mehta
  • 1,658
  • 6
  • 25
  • 34
Kachna
  • 2,921
  • 2
  • 20
  • 34

2 Answers2

0

Depending on the application, catching exceptions intelligently would seem like a good solution. The requirement, however, is that you actually wants to send/do something to the client. Possibly a combination of the two approaches suits your specific application. You could try seeing: Java detect lost connection

Community
  • 1
  • 1
Bjerrum
  • 108
  • 6
0

The book is wrong, if that's what it really says. isConnected() has nothing to do with whether a socket is currently open. It tells you whether it has ever been connected, which is not at all the same thing.

isOpen() does tell you whether the socket is open, but that doesn't tell you anything about the state of the connection. The test for whether the connection is still open is whether:

  • read() has returned -1
  • readLine() has returned null
  • readXXX() has thrown EOFException for any other X

... all of which indicate that the peer has closed the connection, or

  • any read or write method has thrown an IOException with the text 'connection reset'.
user207421
  • 305,947
  • 44
  • 307
  • 483