diff --git a/src/CNProtocol.cpp b/src/CNProtocol.cpp index 4365243..40d1e56 100644 --- a/src/CNProtocol.cpp +++ b/src/CNProtocol.cpp @@ -234,7 +234,9 @@ CNServer::CNServer(uint16_t p): port(p) {} void CNServer::start() { std::cout << "Starting server at *:" << port << std::endl; // listen to new connections, add to connection list - while (true) { + while (active) { + std::lock_guard lock(activeCrit); + // listen for a new connection SOCKET newConnection = accept(sock, (struct sockaddr *)&(address), (socklen_t*)&(addressSize)); if (!SOCKETINVALID(newConnection)) { @@ -280,4 +282,24 @@ void CNServer::start() { } } +void CNServer::kill() { + std::lock_guard lock(activeCrit); // the lock will be removed when the function ends + active = false; + + // kill all connections + std::list::iterator i = connections.begin(); + while (i != connections.end()) { + CNSocket* cSock = *i; + + if (cSock->isAlive()) { + cSock->kill(); + } + + ++i; // go to the next element + delete cSock; + } + + connections.clear(); +} + void CNServer::killConnection(CNSocket* cns) {} // stubbed lol \ No newline at end of file diff --git a/src/CNProtocol.hpp b/src/CNProtocol.hpp index e587683..6f0041e 100644 --- a/src/CNProtocol.hpp +++ b/src/CNProtocol.hpp @@ -39,6 +39,12 @@ #include #include +#ifdef __MINGW32__ + #include "mingw/mingw.mutex.h" +#else + #include +#endif + /* Packets format (sent from the client): [4 bytes] - size of packet including the 4 byte packet type @@ -125,6 +131,9 @@ protected: struct sockaddr_in address; void init(); + bool active = true; + std::mutex activeCrit; + public: PacketHandler pHandler; @@ -132,6 +141,7 @@ public: CNServer(uint16_t p); void start(); + void kill(); virtual void killConnection(CNSocket* cns); }; diff --git a/src/main.cpp b/src/main.cpp index 1326852..67a155e 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -12,14 +12,8 @@ #endif #include -void startLogin(uint16_t port) { - CNLoginServer server(port); - server.start(); -} - -void startShard(uint16_t port) { - CNShardServer server(port); - server.start(); +void startShard(CNShardServer* server) { + server->start(); } int main() { @@ -36,9 +30,15 @@ int main() { ChatManager::init(); std::cout << "[INFO] Starting Server Threads..." << std::endl; - std::thread loginThread(startLogin, settings::LOGINPORT); - std::thread shardThread(startShard, settings::SHARDPORT); - getchar(); // blocks until input + CNShardServer loginServer(settings::LOGINPORT); + CNLoginServer shardServer(settings::SHARDPORT); + + std::thread shardThread(startShard, (CNShardServer*)&shardServer); + + loginServer.start(); + + shardServer.kill(); + shardThread.join(); #ifdef _WIN32 WSACleanup();