0

After I have created a socket and established a connection I use BufferedReader and PrintWriter to write/read from the socket.

Socket s = new Socket(ip, port);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream());

When I'm done using the socket I close it.

s.close();

This will cause a TCP fin to be sent and leave a half-open TCP connection. Is there any way to detect if a client/server closed it's end of the connection?

Carlj901
  • 1,329
  • 4
  • 24
  • 39
  • Have a look at this [question](http://stackoverflow.com/questions/155243/why-is-it-impossible-without-attempting-i-o-to-detect-that-tcp-socket-was-grac) it should answer to your question with quite a lot of informations. – Carlo Apr 13 '13 at 12:15

1 Answers1

1

This will cause a TCP fin to be sent and leave a half-open TCP connection.

Not quite. It will leave a half-open TCP connection that will issue resets if it receives any more data.

Is there any way to detect if a client/server closed its end of the connection?

Not if you've already closed yours. If you had just issued a write shutdown, you could read until EOS, which would tell you about the peer close, then close the socket. Not much point really unless you really have to achieve simultaneous closes.

user207421
  • 305,947
  • 44
  • 307
  • 483