我需要创建一个服务器,为每个尝试连接到服务器的客户端创建一个新线程。为每个客户端创建的新线程管理客户端,服务器进程监听来自端口的新连接。
我需要在 Unix C 中编码。这是我需要尽快完成的任务的子任务。我是这个领域的新手,因此对创建服务器不太了解。
最佳答案
基本上,您正在寻找的是这样的:
#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);
}
}
这是服务器应用程序的一个非常基本的框架,它为每个传入的客户端连接创建一个不同的线程。如果您不知道什么是bind
、listen
或accept
,请参阅本地手册的第二部分。
关于c - 如何创建一个为每个客户端创建一个新线程的服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10074375/