在c ++窗口中的客户端服务器编程中的多线程

时间:2014-04-19 11:56:53

标签: c++ multithreading sockets client-server

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

    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] ='\0';

    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] ='\0';
        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 failed\n"));
            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 failed\n"));
        nRetCode = 1;
    }

    return nRetCode;
}

1 个答案:

答案 0 :(得分:0)

在MSDN上搜索&#34; CSocket + thread&#34;你会发现这个例子:

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