【问题标题】:multi-threaded chess using winsock使用winsock的多线程国际象棋
【发布时间】:2011-06-11 11:32:01
【问题描述】:

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

这里是部分服务器实现

//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();
}
}

【问题讨论】:

  • 您希望通过将 test.c_str() 转换为 recv 的第二个参数来实现什么?

标签: c++ networking winsock


【解决方案1】:

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

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;
}

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

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

【讨论】:

    猜你喜欢
    • 2015-05-02
    • 2022-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-24
    • 2016-04-04
    • 2014-03-02
    相关资源
    最近更新 更多