tags:

views:

430

answers:

2

How can I detect that a socket is half-open? The case I'm dealing with is when the other side of a socket has sent a FIN and the Ruby app has ACKed that FIN. Is there a way for me to tell that the socket is in this condition?

Take, for example:

require 'socket'

s = TCPServer.new('0.0.0.0', 5010)

loop do
  c = s.accept

  until c.closed?
    p c.recv(1024)
  end
end

In this case, when I telnet into port 5010, I'll see all my input until I close the telnet session. At that point, it will print empty strings over and over as fast as it can.

+1  A: 

This seems to be a duplicate of http://stackoverflow.com/questions/61675/recovering-from-a-broken-tcp-socket-in-ruby-when-in-gets, not sure if it helps any tho!

ba
A: 

If you're reading from the socket and receive a FIN it will effectively show up as EOF on the read. At least that's how it works in most environments that I'm familiar with.

In C I would write it like this:

for ( ; numbytes = recv(... ) ; ) { 
 if (numbytes < 0 ) error();
 if (numbytes == 0 ) break; // socket closed
 do something;
}
Robert S. Barnes