ServerSockets - When Is It Closed/Not Connected?

H

Hal Vaughan

I have a ServerSocket that creates a Socket with ServerSocket.accept().  I
then read data from that Socket's InputStream.  I'm sending data to it with
netcat.  When I stop netcat, there is no indication that I can see that the
connection is gone and netcat's client socket is gone.  I've checked with
Socket.isClosed(), isConnected(), isOutputShutdown(), and
isInputShutdown().  There is no indication that this Socket is no longer
communicating with netcat, which isn't running.

How can I detect this change and shut the Socket when/if its counterpart
shuts down?

Thanks for any help!

Hal
 
E

EJP

Hal said:
How can I detect this change and shut the Socket when/if its counterpart
shuts down?

You will read an EOF from the socket's input stream. At this point,
close the stream, or the socket.

NB see the javadoc for Socket.isClosed(), isConnected(),
isOutputShutdown(), and isInputShutdown(). They are not intended to tell
you about the state of the other end of the connection.
 
M

Missaka Wijekoon

Hal said:
I have a ServerSocket that creates a Socket with ServerSocket.accept(). I
then read data from that Socket's InputStream. I'm sending data to it with
netcat. When I stop netcat, there is no indication that I can see that the
connection is gone and netcat's client socket is gone. I've checked with
Socket.isClosed(), isConnected(), isOutputShutdown(), and
isInputShutdown(). There is no indication that this Socket is no longer
communicating with netcat, which isn't running.

How can I detect this change and shut the Socket when/if its counterpart
shuts down?
You cannot assume or know the state of the socket on the other end.
What if the router in between was unplugged indefinitely? So, you will
have to build into the protocol timeouts or some such mechanism to infer
that the other side has gone away.
 
M

mike

Set the socket timeout.

Something like this:
try {
socket.setSoTimout(60000);
}
catch (SocketException e) {
socket.close();
return;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,434
Messages
2,571,689
Members
48,796
Latest member
Greg L.

Latest Threads

Top