How to create a server which creates a new thread for each client? [closed]

这一生的挚爱 提交于 2019-12-13 10:06:09

问题


I need to create a server which creates a new thread for each client trying to connect to the server. The new thread created for each client manages the client and the server process listens for new connections from the port.

I need to code in Unix C. This is a sub-task of the task I need to finish as soon as possible. I am new to this field and hence do not know much about creating servers.


回答1:


Basically, what you're looking for is something like this :

#include <sys/types.h>
#include <sys/socket.h>
#include <pthread.h>

void* handle_connection(void *arg)
{
    int client_sock = *(int*)arg;
    /* handle the connection using the socket... */
}

int main(void)
{
    /* do the necessary setup, i.e. bind() and listen()... */
    int client_sock;
    pthread_t client_threadid;
    while((client_sock = accept(server_sock, addr, addrlen)) != -1)
    {
        pthread_create(&client_threadid,NULL,handle_connection,&client_sock);
    }
}

This is a pretty basic skeleton for a server application which creates a different thread for every incoming client connection. If you don't know what bind, listen, or accept is, then consult the second section of your local manual.




回答2:


First of all take a look at https://computing.llnl.gov/tutorials/pthreads/ . It's tutorial about thread library for C. Enjoy!



来源:https://stackoverflow.com/questions/10074375/how-to-create-a-server-which-creates-a-new-thread-for-each-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!