听(sock,积压)
:
在我看来,参数backlog限制了连接数。这是我的测试代码:
// server
// initialize the sockaddr of server
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons( 8888 );
bind(...);
listen(sock, 1);
while( (client_sock = accept(...)) )
{
// create a thread for one client
if( pthread_create( &sniffer_thread , NULL , connection_handler , (void*) new_sock) < 0)
{
perror("could not create thread");
return 1;
}
}
// client
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = htons( 8888 );
connect(...);
while(1)
{
scanf("%s" , message);
//Send some data
if( send(sock , message , strlen(message) , 0) < 0)
{
puts("Send failed");
return 1;
}
//Receive a reply from the server
if( recv(sock , server_reply , 2000 , 0) < 0)
{
puts("recv failed");
break;
}
puts("Server reply :");
puts(server_reply);
}
在我自己的 PC 上,我执行正在等待客户端的服务器。
然后我执行两个客户端,它们都可以发送和接收消息。
这是我不明白的地方:
为什么我的服务器可以接受两个不同的客户端(两个不同的套接字)?
我将服务器listen
的backlog
参数设置为1
,为什么仍然可以容纳多个客户端?
最佳答案
来自the man
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.
强调我的
在您的情况下,这意味着如果请求同时连接,其中一个连接可能会收到错误。
关于c - 套接字 : listen with backlog and accept,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41102901/