Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;

    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
620 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...