套接字:收听积压并接受
socket: listen with backlog and accept
listen(sock, backlog)
:
在我看来,参数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
,为什么还能容纳多个client?
来自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.
强调我的
在您的情况下,这意味着 如果请求同时连接,其中一个可能会收到错误消息。
listen(sock, backlog)
:
在我看来,参数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
,为什么还能容纳多个client?
来自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.
强调我的
在您的情况下,这意味着 如果请求同时连接,其中一个可能会收到错误消息。