"Bill W." <sirwillard42 / gmail.com> wrote:
> I don't claim to be much of a programmer, and I am also new to RUBY, so
> hopefully this is a good question.

I'll try to explain things with that in mind (but feel free to ask for
clarification)

> I am making a client that can connect to a port and read an unknown
> number of lines, like a server banner.
> Since the server doesn't close the connection, the program will not move
> on.  To overcome this, I used select() with a timeout, so it will read
> whatever is in the pipe and move on if it gets nothing more within n
> seconds.
> 
> Everything worked fine, until I tried crashing the server.  I started to
> get a string of nil coming into the client.

Any method of crashing/terminating the server process (but not the
operating system) causes the operating system/networking stack to close
the TCP connection[1].  This shutdown should be the same as if the
server code explicitly closed it.

> If you kill the server before select() times out, you will get an
> infinite loop of 'nil' in the client.

<snip>

> I could use this 'nil' to show that the server has crashed, but I can't
> help but think it is a symptom of something I've done terribly wrong
> that works for now but will bite me in the future.

It'll work in the future.  Break out of the loop if you get nil and
close the socket in the client, too.

> Any thoughts on where this 'nil' is from?

The TCPSocket#gets method is actually IO#gets (an inherited method from
IO, as TCPSocket is a subclass of IO).

If you read the documentation (`ri IO#gets`), you'll see IO#gets
returns nil on the end-of-file condition, indicating there's nothing
left to be done and the IO object should be closed.


Keep in mind you won't be reliably notified in many failure cases (e.g.
the entire server crashing (OS/hardware/power failure), or a link-level
failure (cables cut, switch fails, ...), so you'll still have to rely
on select() to timeout those cases.


[1] If the crashed process is the only process with that connection,
    but that appears to be the case for you.

-- 
Eric Wong