Socket isClosed() returns false after client disconnected
There is no "disconnect" with TCP. A peer can only indicate that it does not want to send anything more (send FIN) but this does not mean that it does not want to receive anything. The other end only realizes that read is unwanted too once it tries it and gets a RST back.
If you take the "don't want to read" as an indicator that the client closed (you might if the application protocol is this way) then you can test if the peer "disconnected" by simply reading from the socket. The system call then returns no error but 0 bytes and this means that there will be no more data from the peer. In Java this case gets translated into an EOFException.
Apart from that a socket does not get closed automatically - only explicitly. isClosed
only returns true once the socket is explicitly closed on your local end, not the peer's end. And isConnected
will also not tell you if the other end "disconnected", it will only tell you if your end did connect to the peer.
See also Java Socket API: How to tell if a connection has been closed?.
Checking if socket is still open
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.
Related Topics
Regular Expression for Uppercase Letters in a String
Null Pointer on an Autowired Bean Which Is Not Mocked by Mockito
How to Get All Members of Ad Group Via Ldap in Java
Javax.Validation - Allow Null But Validate If the Value Is Not
Spring Boot Could Not Resolve Placeholder in String
How to Solve Liquibase Checksum Validation Fail After Liquibase Upgrade
Open Pdf from Bytes Array in Angular 5
How to Launch Command in Batch File With Space
Java - How to Write My Arraylist to a File, and Read (Load) That File to the Original Arraylist
Java: How to Print Array Without Square Brackets and Commas
How to Get Summation of Pair(Key) Values in a Map in Java
Junit 5 - No Parameterresolver Registered for Parameter
Loop Over All Fields in a Java Class
Resource from Src/Main/Resources Not Found After Building With Maven
@Autowired - No Qualifying Bean of Type Found for Dependency