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:

  1. 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.

  2. 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.

  3. 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:

  1. When the connection completes successfully, the descriptor becomes writable (p. 531 of TCPv2).

  2. 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.

非阻塞connect的三种用法:

1、 三次握手过程可以和其他操作重叠进行。

2、 可以同时建立多个连接。这种做法在浏览器中很常见。

3、可以利用select来缩短connect的等待时间。各种版本的select超时时间从75s到几分钟。

 

其他需要考虑的细节:

如果复位端和客户端在一个主机上,connect函数可能立即返回(三次握手已经完成),必须考虑这种场景。

Berkeley-derived和POSIX系统处理select和非阻塞connect时有如下规则:

1. 连接成功建立时,描述符变为可写;

2. 连接过程出现错误时,描述符变为可读可写。

 

posted on 2014-04-28 16:39  escoffier  阅读(277)  评论(0编辑  收藏  举报