函数原型:
int listen(int sockfd, int backlog);
作用是用来监听服务器创建的socket的。
第二个参数backlog代表的是相应的socket可以排队的最大连接数。
由于客户端client 发起connect()连接时。需要建立TCP三次握手连接需要时间,所有会有一个队列来存储客户端对服务器发起的connect连接。
- 当客户端完成连接后。连接被放到端口的socket的队列里面,等待服务器去响应。
- 当服务器调用accept()来获取队列中的连接,这时候就会从队列中移除。
- listen()函数的第二个参数就是去设置这个队列的大小的。
backlog的上限值受到系统全局设定的限制。
这个上限存储在:/proc/sys/net/core/somaxconn文件中。(我的Ubuntu中设置的最大值是128)。如果大于这个值,就会被截短。
SYNOPSIS
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
int listen(int sockfd, int backlog);
DESCRIPTION
listen() marks the socket referred to by sockfd as a passive socket, that is, as a socket that will be used to accept incoming connection requests using accept(2).
The sockfd argument is a file descriptor that refers to a socket of type SOCK_STREAM or SOCK_SEQPACKET.The backlog argument defines the maximum length to which the queue of pending connections for sockfd may grow. If a connection request arrives when the queue is full, the client may receive an error with an indication of ECONNREFUSED or, if the underlying protocol supports retransmission, the request may be ignored so that a later reattempt at connection succeeds.
RETURN VALUE
On success, zero is returned. On error, -1 is returned, and errno is set appropriately.