How Can I Add Support for Multiple Client Connections to my TCP Server?

  • Thread starter Thread starter James889
  • Start date Start date
  • Tags Tags
    Multiple
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
1 reply · 2K views
James889
Messages
190
Reaction score
1
Hi,

I have a simple tcp server, to which i would like to add support for multiple client connections via pthreads. This is what i had in mind, calling accept in a separate thread.

I this similar to what you would do?

Code:
   .
   .
   .
int sock = socket(PF_INET,SOCK_STREAM,0);
int sock_fd[10];
struct sockaddr_in client_addr[10];
int size = sizeof(&client_addr);

void *Thread1(void *arg){


   for(i=0;i<9;i++){
  sock_fd[i] = accept(sock,(struct sockaddr *)&client_addr[i],size);

}
 
Physics news on Phys.org
No.

Normally accept is blocking until new incoming connection.
So, simplest way would be like this:

Code:
void* ConnectionThread(void* pv)
{
    int fd=(int)pv;
    //...
    close(fd);
    return 0;
}

void main_loop(unsigned short port)
{
    struct sockaddr_in loacal_addr;
    local_addr.sin_family=AF_INET;
    local_addr.sin_port=((port>>8)|(port<<8));
    local_addr.sin_addr.s_addr=INADDR_ANY;

    int lfd=socket(AF_INET,SOCK_STREAM,0);
    if(0!=bind(lfd,(struct sockaddr*)&local_addr,sizeof(local_addr)){
        perror("bind");
    };
    listen(lfd,5);
    while(true){
        struct sockaddr_in remote_addr;
        socklen_t slen=sizeof(remote_addr);
        int afd=accept(lfd,(struct sockaddr*)&remote_addr,&slen);
        if(afd==-1){
            perror("accept");
        }else{
            if(0!=pthread_create(0,0,ConnectionThread,(void*)afd)){
                close(afd);
            };
        };
    };
}
Also there is an option of using asynchronous non-blocking operations instead of/ or in mix with multithreading