在c++windows中进行客户端-服务器程序设计的多线程

Multithread in client server programming in c++ windows

本文关键字:服务器 程序设计 多线程 客户端 c++windows      更新时间:2023-10-16

我有一个问题,如何同时向客户端发送字符串。我的程序将客户端放在一个队列中,所以当第一个客户端断开连接时,第二个客户端连接,我真的想把它们放在多线程中,但我不知道怎么做,任何人都请帮助我,谢谢。

    void abc(CSocket sockClients[],int i)
{
    int MsgSize;
    char *temp;
    // Nhan username tu Server
    sockClients[i].Receive((char*)&MsgSize,sizeof(int),0); // Neu nhan loi thi tra ve la SOCKET_ERROR.           
    temp = new char[MsgSize +1];
    sockClients[i].Receive((char*)temp,MsgSize,0);
    // In username ra
    temp[MsgSize] ='';
    int score=3;
    int ques;
    sockClients[i].Receive((char*)&ques,sizeof(int),0);
    ifstream CH;
    CH.open("cauhoi.txt",ios::in);
    ifstream DA;
    DA.open("dapan.txt",ios::in);
    for(int j=0;j<ques;j++)
    {
        char* CH_SV=new char;
        CH>>CH_SV;
        int Size = strlen(CH_SV);
        sockClients[i].Send(&Size,sizeof(int),0);
        sockClients[i].Send(CH_SV,Size,0);
        char* DA_SV=new char;
        DA>>DA_SV;
        char *dapan;
        sockClients[i].Receive((char*)&Size,sizeof(int),0);
        dapan = new char[Size +1];
        sockClients[i].Receive((char*)dapan,Size,0);
        dapan[Size] ='';
        cout<<"nDap an la: "<<dapan<<endl;
        if(Size<5)
            goto Exit;
        else if(strcmp(dapan,DA_SV)==0)
            score+=2;
        else score--;
    }

    sockClients[i].Close();
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
    int nRetCode = 0;
    HMODULE hModule = ::GetModuleHandle(NULL);
    if (hModule != NULL)
    {
        // initialize MFC and print and error on failure
        if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0))
        {
            // TODO: change error code to suit your needs
            _tprintf(_T("Fatal Error: MFC initialization failedn"));
            nRetCode = 1;
        }
        else
        {
            // TODO: code your application's behavior here.
            CSocket server;
            AfxSocketInit(NULL);
            server.Create(3456);
            server.Listen();
            int nclient;
            cout<<"Nhap so luong client: ";
            cin>>nclient;
            CSocket * sockClients = new CSocket[nclient];
            for (int i = 0; i <nclient; i++)
            {   
                server.Accept(sockClients[i]);
                printf("nClient: %d/%d",i+1,nclient);
                sockClients[i].Send((char*)&i,sizeof(int),0);       
                abc(sockClients,i);
            }
            server.Close();
        }
    }
    else
    {
        // TODO: change error code to suit your needs
        _tprintf(_T("Fatal Error: GetModuleHandle failedn"));
        nRetCode = 1;
    }
    return nRetCode;
}

在MSDN中搜索"CSocket+thread",您会发现以下示例:

http://support.microsoft.com/kb/175668/en-us