TCP Winsock: accept multiple connections/clients

前端 未结 2 1930
梦毁少年i
梦毁少年i 2020-12-06 08:28

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.



        
2条回答
  •  南笙
    南笙 (楼主)
    2020-12-06 09:20

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

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

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

    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.

提交回复
热议问题