...
 
Commits (3)
......@@ -12,7 +12,17 @@ using namespace std;
GameClient::~GameClient()
{
disconnect();
if(networkThread)
networkThread.reset(nullptr);
peer = nullptr;
if(host != nullptr)
enet_host_destroy(host);
host = nullptr;
connected = false;
}
bool GameClient::connect(enet_uint32 hostAddress, enet_uint16 port)
......@@ -54,6 +64,8 @@ bool GameClient::connect(enet_uint32 hostAddress, enet_uint16 port)
return false;
}
outgoingPacketQueue = std::queue<std::string>();
networkThread = unique_ptr<thread>(new thread(&GameClient::networkLoop, this));
networkThread->detach();
......@@ -62,16 +74,7 @@ bool GameClient::connect(enet_uint32 hostAddress, enet_uint16 port)
void GameClient::disconnect()
{
if(networkThread)
networkThread.reset(nullptr);
if(host != nullptr)
enet_host_destroy(host);
peer = nullptr;
host = nullptr;
connected = false;
enet_peer_disconnect (peer, 0);
}
void GameClient::sendPacket(const std::string& packet)
......@@ -86,7 +89,12 @@ void GameClient::networkLoop()
while(true)
{
if(!host || !peer)
{
return;
}
if(!connected)
continue;
outgoingPacketMutex.lock();
if(!outgoingPacketQueue.empty())
......@@ -118,6 +126,11 @@ void GameClient::networkLoop()
cout << "Disconnected from server" << endl;
connected = false;
peer = nullptr;
enet_host_destroy(host);
host = nullptr;
if(eventCallback)
eventCallback(DISCONNECTED);
......
......@@ -43,6 +43,12 @@ public:
return connected;
}
void clearCallbacks()
{
eventCallback = nullptr;
packetCallback = nullptr;
}
void setEventCallback(const EventCallback &callback) {
eventCallback = callback;
}
......@@ -56,7 +62,7 @@ public:
private:
std::unique_ptr<std::thread> networkThread;
std::mutex outgoingPacketMutex;
std::queue<std::string> outgoingPacketQueue;
......
......@@ -73,6 +73,8 @@ void GameServer::stop()
enet_host_destroy(host);
host = nullptr;
started = false;
}
void GameServer::sendPacketToClient(unsigned int clientID, const std::string &packet)
......