如何创建为每个客户端的一个新线程的服务器? [英] How to create a server which creates a new thread for each client?

查看:124
本文介绍了如何创建为每个客户端的一个新线程的服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个为每个客户端试图连接到服务器上创建一个新线程的服务器。为每个客户端创建的新的线程管理在客户端和服务器进程侦听来自端口的新连接。

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.

我需要在Unix中C. code这是我需要尽快完成任务的一个子任务。我是新来这个领域,因此不知道很多有关创建服务器。

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.

推荐答案

基本上,你要找的东西是这样的:

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

这是它创建为每一个客户端连接不同的线程服务器应用程序pretty基本骨架。如果你不知道什么是绑定接受,那么请咨询当地手册的第二部分。

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.

这篇关于如何创建为每个客户端的一个新线程的服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆