开发者

Dynamic multi-thread server problem

 while(true)
        {
        Klient temp;
        SOCKET client = accept(sock,(struct sockaddr *)&ich,&sin_size);
        if (client!= INVALID_SOCKET)
                        {
                                int ID = wszyscy.size(); //wszyscy is a vector of Klient structure; ID increments like: 0,1,2,3 etc
                                memset(&temp,0,sizeof(Klient)); //zero structure
                                temp.Gniazdo = client; //fill temporary structure
                                temp.Identyfikator = ID;
                                temp.Nick = "";
                                temp.Watek = NULL;
                                wszyscy.push_back(temp);//Adding
                                std::cout <&l开发者_StackOverflow中文版t; ID << std::endl; //Showing ID for test
                                std::cout << inet_ntoa(ich.sin_addr) << std::endl;//IP 
                                wszyscy[ID].Watek = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE) Watek,&wszyscy[ID], 0 ,NULL);//Creating thread
        }
    }

Thread:

DWORD Watek(LPVOID Dane)
{
        const char* tekst_serwera = "Halo, tu server :D\n\0";
        Klient *temp = (Klient*) Dane;
        send(temp->Gniazdo,tekst_serwera,strlen(tekst_serwera),0);
        std::cout << "Podlaczyl sie klient o ID: " << temp->Identyfikator << std::endl;
        char bufor[500];
        while(true)
        {
                memset(bufor,0,500);
                recv(temp->Gniazdo,bufor,500,0);
                std::cout << bufor;
        }
} 

The problem is when I launch 2 or more clients, server send to them as it suppose to welcome messages(tekst_servera) but when I write something on client who has been launched as second and then I try to write something on client who has been launched as first server is getting 80%CPU usage and does not receive data, only the first one(It happens only on client who has been launched as first) When I did temp.watek = CreateThread and then push_back server was still not responding to client number 1 messages but was not lagging like hell.

Any help appreciated


According to winsock documentation (msdn.microsoft.com), the recv function will return one of the following values:

  • positive: The number of bytes received;
  • zero: connection was closed;
  • negative: an error has occurred.

I strongly suggest checking the return value of recv(), and terminating the loop when necessary, because in both the zero and negative cases, you'll be stuck in a loop, calling recv() which returns without blocking immediately. This would show up as high CPU usage and non-responsive server threads.

In any case, throwing away the return value from a function you call is bad form, and should only be done in exceptional situations.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜