I am currently stuck in a situation where I initialize a thread and launch it, but it seems to halt my main. Here are the affected files:
#include "ClientHandler.hpp"
#include <algorithm>
#include <iostream>
ClientHandler::ClientHandler()
{
}
void ClientHandler::addConnection(PlayerSession player)
{
mUsers.push_back(player);
Heartbeat beat(player.getIp());
mHeartbeat.push_back(&beat);
std::cout << "Finished adding connection + started heartbeat!" << std::endl;
}
Heartbeat::Heartbeat(sf::IpAddress ip)
: mThread(std::bind(&Heartbeat::heart, this, ip))
{
mThread.launch();
}
void Heartbeat::heart(sf::IpAddress ip)
{
bool isAlive = true;
sf::UdpSocket sock;
sf::Packet packet;
sf::IpAddress recIp;
unsigned short recPort;
sock.bind(54001);
while(isAlive)
{
sf::sleep(sf::milliseconds(1000));
sendHeartbeat(ip);
std::cout << "In Heartbeat! " << std::endl;
if(sock.receive(packet, recIp, recPort) != sf::Socket::Done)
{
std::cout << "SOMETHING WENT WRONG WHEN TRYING TO RECEIVE" << std::endl;
isAlive = false;
}
int x;
if(packet >> x)
{
if(x == ClientPacket::ReplyHeartbeat)
{
std::cout << "RECIEVED REPLY HEARTBEAT" << std::endl;
}
if(x == ClientPacket::PlayerConnect)
{
std::cout << "THIS ISN'T SUPPOSED TO BE HAPPENING HERE!" << std::endl;
}
}
}
}
void ServerCore::enterServerLoop()
{
if(mSocket.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 received;
if(mSocket.receive(packet, ip, port) != sf::Socket::Done)
{
}
int x;
if(packet >> x)
{
std::cout << x << std::endl;
if(x == ClientPacket::PlayerConnect)
{
std::cout << "Player Connected!" << std::endl;
sf::Packet sPacket;
sf::String username;
packet >> username;
PlayerSession user(ip, username);
mClients.addConnection(user);
std::cout << "AFTER ADDCONNECTION(USER)" << std::endl;
std::cout << mClients.size() << std::endl;
sPacket << ServerPacket::ServerStop;
std::cout << sPacket << " " << ip << " " << (std::string)username << std::endl;
//TESTING THE BROADAST IP
if(mSocket.send(sPacket, ip, 54000) != sf::Socket::Done)
{
std::cout << "I AM SAD" << std::endl;
}
...
Here is the server output log:
PREPARING USER DATABASE
Initialized Server
:D
1
Player Connected!
Finished adding connection + started heartbeat!
In Heartbeat!
RECIEVED REPLY HEARTBEAT
In Heartbeat!
RECIEVED REPLY HEARTBEAT
In Heartbeat!
RECIEVED REPLY HEARTBEAT
In Heartbeat!
RECIEVED REPLY HEARTBEAT
In Heartbeat!
RECIEVED REPLY HEARTBEAT
In Heartbeat!
The print after the addConnection call is never reached. Any suggestions?