使用winsock的多线程国际象棋

时间:2011-06-05 15:31:26

标签: c++ networking winsock

我一直致力于基于小型网络的国际象棋应用程序。我设法创建了一个可以处理多个连接的服务器,但是我不知道如何将数据从一个客户端发送到另一个客户端。

这是部分服务器实现

//function to handle our Socket on its own thread.
//param- SOCKET* that is connected to a client
DWORD WINAPI HandleSocket(void* param)
{
string test;

SOCKET s = (SOCKET)param;
User temp;
temp._socket = (SOCKET)param;
temp._inGame = false;
userlist.add(&temp);

std::cout<<"connection"<<endl;
int bytesread = 0;  
int byteswrite=0;

while(true)
{
    //receive
    bytesread = recv(s, reinterpret_cast<char*>(test.c_str()), BUF_LEN, 0);

    //error check   
    if(bytesread == SOCKET_ERROR)
    {
        std::cout << WSAGetLastError();
        //shutdown and close on error
        shutdown(s, SD_BOTH);
        closesocket(s);
        return 0;
    }


    //check for socket being closed by the client
    if(bytesread == 0)
    {
        //shutdown our socket, it closed
        shutdown(s, SD_BOTH);
        closesocket(s);
        return 0;
    }

    byteswrite = send(s, "test" , 255 , 0);
    if(byteswrite == SOCKET_ERROR)
    {
        std::cout << WSAGetLastError();
        //shutdown and close on error
        shutdown(s, SD_BOTH);
        closesocket(s);
        return 0;
    }

    test.clear();
}
}

1 个答案:

答案 0 :(得分:2)

当游戏的两个玩家都连接到服务器时,也许你应该为新游戏开始一个线程。在这种情况下,您可以通过以下方式将两个套接字传递给线程:

DWORD WINAPI HandleGame(void* param)
{
    GameState* game = (GameState*)param;
    SOCKET s1 = game->getSocketOfPlayer(1);
    SOCKET s2 = game->getSocketOfPlayer(2);
    ...
    // TODO: Forward game messages between clients (players).    
    ...
    delete game;
    return 0;
}

替代解决方案:在sigle线程中实现服务器程序。

在这两种情况下,您都需要select()函数来同时等待来自多个玩家的消息。