TCP Winsock:接受多个连接/客户端 [英] TCP Winsock: accept multiple connections/clients

查看:127
本文介绍了TCP Winsock:接受多个连接/客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着可以乘客户,并发送给每一个。
但是它只能工作一个,一个客户端连接后,服务器只是无用的连接。

I tried to can multiply clients, and send it to each one. But it working only for one, after one client connected the server just useless for incoming connections.

while(true)
{
    if(Sub = accept(Socket, (sockaddr*)&IncomingAddress, &AddressLen))
    {
        for(int i = 0; i < MaxUsers; i++)
        {
            if(!ClientAddress[i].sin_family)
            {
                ClientAddress[i] = IncomingAddress;
                char Version[128], Dir[256], Path[256], URL[128], Message[256];
                GetCurrentDirectory(256, Dir);
                sprintf(Path, "%s\\Version.ini", Dir);
                GetPrivateProfileString("Default", "Version", "1.0.0.0", Version, 128, Path);
                GetPrivateProfileString("Default", "URL", "", URL, 128, Path);
                GetPrivateProfileString("Default", "Message", "", Message, 256, Path);
                send(Sub, Version, 128, 0);
                send(Sub, Message, 256, 0);
                break;
            }
        }
        continue;

    }
}


推荐答案

当然,新客户端无法被接受,因为服务器只处理刚接受的客户端,即服务器正忙。

Of course new clients cannot be accepted because the server handles just accepted client, i.e. the server is busy.

解决方案很简单:为每个客户端创建一个新线程接受客户端并处理客户端会话。只需使用 _beginthreadex() #include< process.h> ):

The solution is simple: create a new thread for each accepted client and handle the client session there. Just use _beginthreadex() (#include <process.h>):

unsigned __stdcall ClientSession(void *data)
{
    SOCKET client_socket = (SOCKET)data;
    // Process the client.
}

int _tmain(int argc, _TCHAR* argv[])
{
    ...

    SOCKET client_socket;
    while ((client_socket = accept(server_socket, NULL, NULL))) {
        // Create a new thread for the accepted client (also pass the accepted client socket).
        unsigned threadID;
        HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &ClientSession, (void*)client_socket, 0, &threadID);
    }
}

顺便说一下, send ()/ recv()函数不保证会在一次调用中发送/接收所有数据。请参阅这些函数的返回值的文档。

By the way, send()/recv() functions do not guarantee that all the data would be sent/received at one call. Please see the documentation for return value of these functions.

这篇关于TCP Winsock:接受多个连接/客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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