Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Multiple client connections

  1. Feb 3, 2013 #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 (Text):

       .
       .
       .
    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);

    }
     
     
  2. jcsd
  3. Feb 7, 2013 #2
    No.

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

    Code (Text):

    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
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Multiple client connections
  1. Client server (Replies: 2)

Loading...