非阻塞I/O 复用-conncet

王朝学院·作者佚名  2016-05-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

非阻塞I/O 复用-conncetWhen 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.

非阻塞connect的三种用法:

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

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

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

其他需要考虑的细节:

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

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

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

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

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航