Please enable JavaScript to view this site.

A-Shell Consolidated Reference

Navigation: Development Topics > Socket Programming > Scenarios and Issues

Non-Blocking, Checking Without Waiting

Scroll Prev Top Next More

One possible shortcoming with the implementation just described is that both client and server are "hung" during the read operation (waiting for the other end to send something.) If the remote end malfunctions, the local side would become more or less incapacitated. (You could ^C out of the wait state, but that is of little benefit to an unattended process.) The danger of this happening is minimal in the simple server just described, but in some cases, it could perhaps be more of a concern. In that case, you may want to employ one of the following techniques.

The first is simply to check for input (using Opcode 7) before invoking the read operation. Since you can set a timer on the check operation, you can be certain of not getting stuck. The main problem with Opcode 7 is that it can only tell you if there is data to read, not how much. Consequently, in order to achieve maximum robustness, you would need to program for the possibility of receiving a fragmented packet. (See the following discussion on packet fragmentation.) A better solution to that problem is Opcode 8, which will tell you how many characters are available. Perhaps better still would be to use the TIMER parameter to set the maximum time to a very short interval, and the FLAGS parameter to the number of characters you want to wait for. (This is a new capability added to TCPX that was not supported by the earlier routines.)

An alternate approach is to open the socket with FLAGS=0 (i.e. to clear the blocking flag.) In that case, an attempt to read (or write) to a socket that is unable to supply (or receive) any data will return an error code rather than hanging the process. Under Windows the normal error code is -10035 (Operation Would Block.) Under Unix, it is typically –11 (Resource Unavailable.) When such an error occurred on a read or write call, the application would want to loop and retry after a short wait.

Even in the non-blocking case, an active close at the remote end will be indicated by a return STATUS of 0 to a read call. An attempt to write to a socket that has been closed by the remote end may accept a few characters but will eventually return an error such as –32 (Broken Pipe).