http://qs321.pair.com?node_id=281442


in reply to Re: Re: Detecting a closed socket
in thread Detecting a closed socket

UPDATE: The poster was using the return of read(), not write(). This still isn't safe under all circumstances, but it should be safe as long as the socket is blocking, and there is no requirement for the server application to switch between multiple clients. In the servers that I normally write, I always have to switch between multiple clients, therefore I always choose to use non-blocking sockets, with all read() and write() operations performed by a buffering layer.

Detecting failure on write() only allows you to clean up 'dead' sockets when you get around to writing to the sockets. This can be sub-optimal if write() is issued infrequently.

Also, write() only guarantees that the bytes make it to a system buffer, it does not guarantee that the socket is still 'open'. If the socket is blocking (the default), write()'s larger than the size of the system buffer will block, holding the entire server process up. If the socket is non-blocking (see IO::Handle::blocking()) write()'s may return with fewer bytes (usually, the room left in the system buffer before it is filled), but this does not mean that the socket is closed. It just means you have to complete the write() at a later time.

Somebody else suggested that you use Net::Server. The reason for this suggestion is that socket manipulation is not always intuitive, and it is frequently more complex than most people want to understand. Server applications implemented using logic like "syswrite(4) must return 4" may work in the present, because 4 is significantly less than the size of a system buffer, but what happens when more bytes are written, and the system buffer gets filled? The server can fail, and the failure can be difficult to reproduce or solve later.

Cheers,
mark