问题
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