16.3 Nonblocking connect
When a TCP socket is set to nonblocking and then connect is called, connect returns immediately with an error of EINPROGRESS but the TCP three-way handshake continues. We then check for either a successful or unsuccessful completion of the connection's establishment using select. There are three uses for a nonblocking connect:
We can overlap other processing with the three-way handshake. A connect takes one RTT to complete (Section 2.6) and this can be anywhere from a few milliseconds on a LAN to hundreds of milliseconds or a few seconds on a WAN. There might be other processing we wish to perform during this time. We can establish multiple connections at the same time using this technique. This has become popular with Web browsers, and we will show an example of this in Section 16.5. Since we wait for the connection to be established using select, we can specify a time limit for select, allowing us to shorten the timeout for the connect. Many implementations have a timeout for connect that is between 75 seconds and several minutes. There are times when an application wants a shorter timeout, and using a nonblocking connect is one way to accomplish this. Section 14.2 talks about other ways to place timeouts on socket operations.
As simple as the nonblocking connect sounds, there are other details we must handle:
Even though the socket is nonblocking, if the server to which we are connecting is on the same host, the connection is normally established immediately when we call connect. We must handle this scenario. Berkeley-derived implementations (and POSIX) have the following two rules regarding select and nonblocking connects:
When the connection completes successfully, the descriptor becomes writable (p. 531 of TCPv2). When the connection establishment encounters an error, the descriptor becomes both readable and writable (p. 530 of TCPv2). These two rules regarding select fall out from our rules in Section 6.3 about the conditions that make a descriptor ready. A TCP socket is writable if there is available space in the send buffer (which will always be the case for a connecting socket since we have not yet written anything to the socket) and the socket is connected (which occurs only when the three-way handshake completes). A pending error causes a socket to be both readable and writable.
There are many portability problems with nonblocking connects that we mention in the examples that follow.
|