Hello. I am making multiplayer game. Currently, I want to implement playing on 1 computer. My idea is to start TCP server on localhost and connect clients in game screen here. But my server freezes whole program, so the render loop of the screen doesn't start. Also, I cannot receive my data (it has 0 size and trash in value)
My Server (
please, ignore Logger class, it is just basic file stream logger):
struct ServerPlayer {
TcpSocket sock;
std::string name;
int turns;
};
class GameServer {
public:
bool start(unsigned short port);
//Handle gameplay
void handleMove(int target, int x, int y);
void handleAttack(int target, int attacker);
void handleSpell(int target, int spell);
void handleSkip();
void parsePacket();
void shutdown(string msg);
private:
bool isRunning;
TcpListener listener;
Logger logger;
vector<ServerPlayer> players;
};
Implementation of start method:
bool GameServer::start(unsigned short port)
{
logger.open("server.log");
logger.log("Starting game server on port "+patch::to_string(port));
if (listener.listen(port) != sf::Socket::Done)
{
logger.log("ERROR: Cannot start listening on given port!");
logger.close();
return false;
}
logger.log("Now listening to incoming connections...");
sf::TcpSocket client;
isRunning = true;
while (isRunning) {
if (listener.accept(client) == sf::Socket::Done) {
Packet p;
p << HANDSHAKE;
client.send(p);
}
}
logger.close();
}
How I start my server:
void startServer() {
server.start(GAMEPORT);
}
...
Thread serverThread(&startServer);
serverThread.launch();
TcpSocket sock;
sf::TcpSocket socket;
sf::Socket::Status status = socket.connect("127.0.0.1", GAMEPORT);
if (status != sf::Socket::Done)
{
printf("ERROR: cannot connect to server!");
}
Packet p;
sock.receive(p);
int msg;
if (p >> msg) {
} else {
printf("ERROR: couldn't receive data\n");
}
printf("Received packet from Server: %d of %d bytes\n", msg, p.getDataSize());
I hope you will help me and my code isn't too big to read
.
Regards,
MrOnlineCoder