Search code examples
clinuxsocketsserverlisten

socket: listen with backlog and accept


listen(sock, backlog):
In my opinion, the parameter backlog limits the number of connection. Here is my test code:

// 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);
}

On my own PC, I execute the server, which is waiting for clients.
Then I execute two clients, both of them can send and receive messages.

Here is what I don't understand:
Why does my server can accept two different clients (two different sockets)?
I set the parameter of backlog as 1 for the listen of the server, why does it can still hold more than one client?


Solution

  • From 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.

    Emphasis mine

    In your case it means that if simultaneous connections are requested one of those can receive back an error.