c - 套接字 : listen with backlog and accept

标签 c linux sockets server listen

听(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 上,我执行正在等待客户端的服务器。
然后我执行两个客户端,它们都可以发送和接收消息。

这是我不明白的地方:
为什么我的服务器可以接受两个不同的客户端(两个不同的套接字)?
我将服务器listenbacklog参数设置为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/

相关文章:

linux nasm 程序集 dwtoa

c - 如何在c中的套接字编程中从服务器程序调用另一个服务器程序

c - 保存链接列表以供以后使用

c - K&R练习4.5 math.h函数作用于C语言中的波兰语反向计算器问题

linux - 将大量文件分发到较小的组的脚本

linux - 当用户从特定主机通过 SSH 登录时执行操作

c++ - 如何将一个数字分成几个不等但递增的数字[用于发送 PlaceOrder( OP_BUY,lots ) 合约 XTO ]

c - 函数返回结构错误

Java - 无法与 ServerSocket 连接

multithreading - 在 Tomcat 中用打开的套接字杀死线程