我正在尝试使用UDP和数据包来创建用于游戏开发的网络框架。我能够接收从客户端发送到服务器的数据包,但是当服务器尝试发送数据包以响应它收到的数据包时,套接字的状态将设置为Error并且不发送数据包。以下是受影响的服务器代码:
服务器.cpp文件:
#include "ServerCore.hpp"
#include "Packet.hpp"
#include <SFML/Network/IpAddress.hpp>
#include <iostream>
ServerCore::ServerCore(int port)
: mSocketRecv()
, mSocketSend()
{
mPort = port;
}
void ServerCore::enterServerLoop()
{
if(mSocketRecv.bind(mPort) != sf::Socket::Done)
{
std::cout << "SOMETHING DIDNT WORK" << std::endl;
}
std::cout << "Initialized Server" << std::endl;
unsigned short port;
sf::IpAddress ip;
while(true)
{
std::cout << ":D" << std::endl;
sf::Packet packet;
std::size_t recieved;
if(mSocketRecv.receive(packet, ip, port) != sf::Socket::Done)
{
}
int x;
if(packet >> x)
{
if(x == ClientPacket::PlayerConnect)
{
std::cout << "Player Connected!" << std::endl;
sf::Packet packet;
packet << ServerPacket::ServerStop;
if(mSocketSend.send(packet, mSender, 54000) != sf::Socket::Done)
{
std::cout << "I AM SAD" << std::endl;
}
}
if(x == ClientPacket::PlayerDisconnect)
std::cout << "Player Disconnected!" << std::endl;
if(x == ClientPacket::PlayerQuit)
std::cout << "Player Quit!" << std::endl;
if(x == ClientPacket::PlayerJoin)
std::cout << "Player Join!" << std::endl;
}
std::cout << "Recieved " << recieved << " bytes from " << ip << " on port " << port << std::endl;
}
}
服务器.hpp文件:
#pragma once
#include <SFML/Network/UdpSocket.hpp>
#include <SFML/Network/IpAddress.hpp>
#include <SFML/Network/Packet.hpp>
class ServerCore
{
public:
ServerCore(int port);
void enterServerLoop();
private:
sf::UdpSocket mSocketRecv;
sf::UdpSocket mSocketSend;
sf::IpAddress mSender;
int mPort;
};
这是受影响的代码块(特别是未按预期工作的位置):
if(x == ClientPacket::PlayerConnect)
{
std::cout << "Player Connected!" << std::endl;
sf::Packet packet;
packet << ServerPacket::ServerStop;
if(mSocketSend.send(packet, mSender, 54000) != sf::Socket::Done)
{
std::cout << "I AM SAD" << std::endl;
}
}
有关如何解决此问题的任何想法?