TCP Winsock: accept multiple connections/clients

Ido Hadar picture Ido Hadar · Mar 3, 2013 · Viewed 17k times · Source

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;

    }
}

Answer

Sergey Brunov picture Sergey Brunov · Mar 3, 2013

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

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.