2

I would have assumed that calling isConnected() on a socket would tell me whether if is connected to the other side or not.

Returns: true if the socket successfuly connected to a server

but after checking and then calling flush() on the socket I get

java.net.SocketException: Broken pipe

How is isConnected different than isClosed, and what is the real behavior of each?

How do I tell if the other side if officially closed without writing anything to the streams, or creating new connections? Is there even a way?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
rubixibuc
  • 7,111
  • 18
  • 59
  • 98
  • These may help: http://stackoverflow.com/questions/3701073/how-can-a-socket-be-both-connected-and-closed, http://stackoverflow.com/questions/151590/java-how-to-detect-a-remote-side-socket-close, http://stackoverflow.com/questions/10240694/java-socket-api-how-to-tell-if-a-socket-has-been-closed – Anil Vaitla Apr 08 '13 at 00:31
  • 1
    Same question as http://stackoverflow.com/questions/3701073/how-can-a-socket-be-both-connected-and-closed – donramos Apr 08 '13 at 00:33

1 Answers1

8

I would have assumed that calling isConnected() on a socket would tell me whether if is connected to the other side or not.

Wrong. It tells you whether you ever connected this Socket. It doesn't tell you about the state of the connection.

Returns: true if the socket successfuly connected to a server

Note that it doesn't say 'is currently connected' to a server.

How is isConnected different than isClosed, and what is the real behavior of each?

The real behaviour of both is that they tell you what you have done to the socket, not what the state of the connection is.

How do I tell if the other side if officially closed without writing anything to the streams, or creating new connections? Is there even a way?

No there isn't. If the peer closed normally, a read will return an EOS indication (read() returns -1, readLine() retuns null, readXXX() for any other XXX throws EOFException). A write will throw an IOException 'connect reset' or 'broken pipe' depending on your platform. TCP doesn't support anything in the nature of a 'dial tone', so absent a pending write there is no current connection status to enquire on.

user207421
  • 305,947
  • 44
  • 307
  • 483