Home:ALL Converter>socket: listen with backlog and accept

socket: listen with backlog and accept

Ask Time:2016-12-12T22:19:01         Author:Yves

Json Formatter

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?

Author:Yves,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/41102901/socket-listen-with-backlog-and-accept
yy