使用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();
}
}
I've been working on a small network based chess application. I managed to create a server that can handle multiple connections, however I don't know how to send data from one client to another.
Here is the partial Server implementation
//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();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当游戏的两个玩家都连接到服务器时,也许您应该为新游戏启动一个线程。在这种情况下,您可以通过以下方式将两个套接字传递给线程:
替代解决方案:在单线程中实现服务器程序。
在这两种情况下,您可能都需要 select() 函数来同时等待来自多个玩家的消息。
Maybe you should start a thread for a new game when both players of the game are connected to the server. In that case you can deliver both sockets to the thread by the following way:
Alternative solutions: Implement the server program in sigle thread.
In both cases you propably need select() function for waiting messages from several players simultaneously.