TCP三次握手的过程,accept发生在三次握手的哪一个阶段?
答案是:accept过程发生在三次握手之后,三次握手完成后,客户端和服务器就建立了tcp连接并可以进行数据交互了。这时可以调用accept函数获得此连接。
也许这个图描述的更加清晰。
Accept函数的原型是:
int accept(int socket, struct sockaddr *restrict address,socklen_t *restrict address_len);
功能描述的:
The accept() function shall extract the first connection on the queue of pending connections, create a new socket with the same socket type protocol and address family as the specified socket, and allocate a new file descriptor for that socket.
意思就是:accept函数会从已经建立连接的队列中取出第一个连接,并创建一个新的socket,新的socket的类型和地址参数要和原来的那个指定的socket的地址一一样,并且还要为这个新的socket分配文件描述符。
The accepted socket cannot itself accept more connections. The original socket remains open and can accept more connections.
新建的这个socket自身是无法再接收连接了,但是最开始的那个socket仍然是处于开放状态,而且可以接收更多连接。
If the listen queue is empty of connection requests and O_NONBLOCK is not set on the file descriptor for the socket, accept() shall block until a connection is present. If the listen() queue is empty of connection requests and O_NONBLOCK is set on the file descriptor for the socket, accept() shall fail and set errno to [EAGAIN] or [EWOULDBLOCK].
意思就是:在连接的监听队列为空并且O_NONBLOCK 没有置位的情况下,accpet是阻塞的。如果监听队列为空,但是O_NONBLOCK 置位的情况下,accpet会立即返回。