Cody
Cody

Reputation: 890

Checking if socket is still open

I used the Java Knock Knock tutorial for creating a client-server connection but I cant figure out how to check if the socket is still open.

Simplified code:

try {
    while ((clientMessage = inFromClient.readLine()) != null) {
        //do stuff
    } catch (IOException e) {
        //client disconnected
        e.printStackTrace();
    }
}

This works great, however I noticed that when the client is Linux based the exception isn't thrown if client gets forcefully closed. I tried some suggestions posted by others but can't get any working. I tried to implement a loop that checks how long its been since last message was received but it didn't work, the loop had to be inside the loop in the above code, and the loop is only executed when a new message is received from the client. I'm very confused but I don't understand how to implement any methods of checking.

If I put the method to check for inactivity outside the above loop then it's never called because the socket loop is indefinite (unless socket is closed).

Upvotes: 0

Views: 3419

Answers (1)

user207421
user207421

Reputation: 310840

Just set a read timeout with Socket.setSoTimeout(). Set it to higher than the expected request interval, say double that. If it expires, you will get a SocketTimeoutException: close the socket.

Contrary to some of the comments, isConnected(), isBound(), isClosed(), etc. are no use for this. They tell you whether you connected, bound, closed, etc. the Socket. Not about the state of the connection.

Upvotes: 3

Related Questions