From 343a728911991758477b358c7f9f7156e4e60caf Mon Sep 17 00:00:00 2001 From: SoftCoder Date: Wed, 18 Dec 2013 23:35:27 -0800 Subject: [PATCH] - cleanup some network related code and try to remove uneeded noise --- .../glest_game/network/client_interface.cpp | 534 +++----- source/glest_game/network/connection_slot.cpp | 412 +++--- .../glest_game/network/server_interface.cpp | 1117 ++++++++--------- .../sources/platform/posix/socket.cpp | 3 +- 4 files changed, 889 insertions(+), 1177 deletions(-) diff --git a/source/glest_game/network/client_interface.cpp b/source/glest_game/network/client_interface.cpp index 05fccf303..881479158 100644 --- a/source/glest_game/network/client_interface.cpp +++ b/source/glest_game/network/client_interface.cpp @@ -44,8 +44,8 @@ const bool debugClientInterfacePerf = false; // ===================================================== ClientInterfaceThread::ClientInterfaceThread(ClientInterface *client) : BaseThread() { - this->clientInterface = client; - uniqueID = "ClientInterfaceThread"; + this->clientInterface = client; + this->uniqueID = "ClientInterfaceThread"; } ClientInterfaceThread::~ClientInterfaceThread() { @@ -77,23 +77,16 @@ void ClientInterfaceThread::execute() { if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] ****************** STARTING worker thread this = %p\n",__FILE__,__FUNCTION__,__LINE__,this); - //bool minorDebugPerformance = false; - Chrono chrono; - - // Set socket to blocking -// if(clientInterface != NULL && clientInterface->getSocket(true) != NULL) { -// clientInterface->getSocket(true)->setBlock(true); -// } + // Set socket to non blocking if(clientInterface != NULL && clientInterface->getSocket(true) != NULL) { clientInterface->getSocket(true)->setBlock(false); } if(SystemFlags::VERBOSE_MODE_ENABLED) printf("ClientInterfaceThread::exec Line: %d\n",__LINE__); + Chrono chrono; for(;this->clientInterface != NULL;) { - //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("ClientInterfaceThread::exec Line: %d\n",__LINE__); - if(getQuitStatus() == true) { if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); break; @@ -106,11 +99,11 @@ void ClientInterfaceThread::execute() { //printf("ClientInterfaceThread::exec Line: %d\n",__LINE__); uint64 loopCount = 0; - Chrono chrono; if(debugClientInterfacePerf == true) { chrono.start(); } - while(this->getQuitStatus() == false && clientInterface != NULL) { + while( this->getQuitStatus() == false && + clientInterface != NULL) { //printf("ClientInterfaceThread::exec Line: %d this->getQuitStatus(): %d\n",__LINE__,this->getQuitStatus()); clientInterface->updateNetworkFrame(); @@ -129,10 +122,11 @@ void ClientInterfaceThread::execute() { } } - if(debugClientInterfacePerf == true)printf("END === Client thread\n"); + if(debugClientInterfacePerf == true) { + printf("END === Client thread\n"); + } //printf("ClientInterfaceThread::exec Line: %d\n",__LINE__); - //if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); if(getQuitStatus() == true) { if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); @@ -143,7 +137,6 @@ void ClientInterfaceThread::execute() { } if(SystemFlags::VERBOSE_MODE_ENABLED) printf("ClientInterfaceThread::exec Line: %d\n",__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] ****************** ENDING worker thread this = %p\n",__FILE__,__FUNCTION__,__LINE__,this); } @@ -170,51 +163,51 @@ void ClientInterfaceThread::execute() { // class ClientInterface // ===================================================== -const int ClientInterface::messageWaitTimeout= 10000; //10 seconds -const int ClientInterface::waitSleepTime= 10; -const int ClientInterface::maxNetworkCommandListSendTimeWait = 4; +const int ClientInterface::messageWaitTimeout = 10000; //10 seconds +const int ClientInterface::waitSleepTime = 10; +const int ClientInterface::maxNetworkCommandListSendTimeWait = 4; ClientInterface::ClientInterface() : GameNetworkInterface() { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] constructor for %p\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this); - networkCommandListThreadAccessor = new Mutex(CODE_AT_LINE); - networkCommandListThread = NULL; - cachedPendingCommandsIndex = 0; - cachedLastPendingFrameCount = 0; - timeClientWaitedForLastMessage = 0; + networkCommandListThreadAccessor = new Mutex(CODE_AT_LINE); + networkCommandListThread = NULL; + cachedPendingCommandsIndex = 0; + cachedLastPendingFrameCount = 0; + timeClientWaitedForLastMessage = 0; - flagAccessor = new Mutex(CODE_AT_LINE); + flagAccessor = new Mutex(CODE_AT_LINE); - clientSocket= NULL; - sessionKey = 0; - launchGame= false; - introDone= false; + clientSocket = NULL; + sessionKey = 0; + launchGame = false; + introDone = false; - this->joinGameInProgress = false; - this->joinGameInProgressLaunch = false; - this->readyForInGameJoin = false; - this->resumeInGameJoin = false; + this->joinGameInProgress = false; + this->joinGameInProgressLaunch = false; + this->readyForInGameJoin = false; + this->resumeInGameJoin = false; - quitThreadAccessor = new Mutex(CODE_AT_LINE); + quitThreadAccessor = new Mutex(CODE_AT_LINE); setQuitThread(false); - playerIndex= -1; - gameSettingsReceivedCount=0; + playerIndex = -1; + gameSettingsReceivedCount = 0; setGameSettingsReceived(false); - gameSettingsReceivedCount=0; - connectedTime = 0; - port = 0; - serverFTPPort = 0; + gameSettingsReceivedCount = 0; + connectedTime = 0; + port = 0; + serverFTPPort = 0; - gotIntro = false; - lastNetworkCommandListSendTime = 0; - currentFrameCount = 0; - lastSentFrameCount = 0; - clientSimulationLagStartTime = 0; + gotIntro = false; + lastNetworkCommandListSendTime = 0; + currentFrameCount = 0; + lastSentFrameCount = 0; + clientSimulationLagStartTime = 0; - networkGameDataSynchCheckOkMap = false; - networkGameDataSynchCheckOkTile = false; - networkGameDataSynchCheckOkTech = false; + networkGameDataSynchCheckOkMap = false; + networkGameDataSynchCheckOkTile = false; + networkGameDataSynchCheckOkTech = false; this->setNetworkGameDataSynchCheckTechMismatchReport(""); this->setReceivedDataSynchCheck(false); } @@ -222,7 +215,6 @@ ClientInterface::ClientInterface() : GameNetworkInterface() { void ClientInterface::shutdownNetworkCommandListThread(MutexSafeWrapper &safeMutexWrapper) { if(networkCommandListThread != NULL) { //printf("START === shutdownNetworkCommandListThread\n"); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s Line: %d\n",__FUNCTION__,__LINE__); setQuitThread(true); @@ -234,8 +226,10 @@ void ClientInterface::shutdownNetworkCommandListThread(MutexSafeWrapper &safeMut Chrono chronoElapsed(true); for(;chronoElapsed.getMillis() <= 10000;) { safeMutexWrapper.Lock(); - if(networkCommandListThread != NULL && networkCommandListThread->canShutdown(false) == false && + if(networkCommandListThread != NULL && + networkCommandListThread->canShutdown(false) == false && networkCommandListThread->getRunningStatus() == true) { + safeMutexWrapper.ReleaseLock(true); if(chronoElapsed.getMillis() % 1000 == 0) { sleep(1); @@ -252,9 +246,10 @@ void ClientInterface::shutdownNetworkCommandListThread(MutexSafeWrapper &safeMut if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s Line: %d\n chronoElapsed.getMillis(): %lld",__FUNCTION__,__LINE__,(long long int)chronoElapsed.getMillis()); //printf("A === shutdownNetworkCommandListThread\n"); - //sleep(0); safeMutexWrapper.Lock(); - if(networkCommandListThread != NULL && networkCommandListThread->canShutdown(true)) { + if(networkCommandListThread != NULL && + networkCommandListThread->canShutdown(true)) { + if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s Line: %d\n",__FUNCTION__,__LINE__); delete networkCommandListThread; @@ -263,7 +258,6 @@ void ClientInterface::shutdownNetworkCommandListThread(MutexSafeWrapper &safeMut else { networkCommandListThread = NULL; } - //safeMutexWrapper.ReleaseLock(true); if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s Line: %d\n",__FUNCTION__,__LINE__); //printf("END === shutdownNetworkCommandListThread\n"); @@ -272,7 +266,6 @@ void ClientInterface::shutdownNetworkCommandListThread(MutexSafeWrapper &safeMut ClientInterface::~ClientInterface() { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] destructor for %p\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,this); - //printf("START === Client destructor\n"); if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s Line: %d\n",__FUNCTION__,__LINE__); @@ -286,21 +279,24 @@ ClientInterface::~ClientInterface() { if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s Line: %d\n",__FUNCTION__,__LINE__); - if(clientSocket != NULL && clientSocket->isConnected() == true) { + if(clientSocket != NULL && + clientSocket->isConnected() == true) { + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s Line: %d\n",__FUNCTION__,__LINE__); Lang &lang= Lang::getInstance(); const vector languageList = this->gameSettings.getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { + for(unsigned int langIndex = 0; langIndex < languageList.size(); ++langIndex) { + string sQuitText = "has chosen to leave the game!"; - if(lang.hasString("PlayerLeftGame",languageList[i]) == true) { - sQuitText = lang.getString("PlayerLeftGame",languageList[i]); + if(lang.hasString("PlayerLeftGame",languageList[langIndex]) == true) { + sQuitText = lang.getString("PlayerLeftGame",languageList[langIndex]); } if(clientSocket != NULL && clientSocket->isConnected() == true) { - sendTextMessage(sQuitText,-1,false,languageList[i]); + sendTextMessage(sQuitText,-1,false,languageList[langIndex]); } } } @@ -310,19 +306,17 @@ ClientInterface::~ClientInterface() { //printf("B === Client destructor\n"); if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + close(false); + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s Line: %d\n",__FUNCTION__,__LINE__); - //delete clientSocket; - //clientSocket = NULL; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s Line: %d\n",__FUNCTION__,__LINE__); //printf("C === Client destructor\n"); - //Mutex *tempMutexPtr = networkCommandListThreadAccessor; networkCommandListThreadAccessor = NULL; safeMutex.ReleaseLock(false,true); @@ -336,7 +330,6 @@ ClientInterface::~ClientInterface() { quitThreadAccessor = NULL; if(SystemFlags::VERBOSE_MODE_ENABLED) printf("%s Line: %d\n",__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); } @@ -391,7 +384,7 @@ void ClientInterface::connect(const Ip &ip, int port) { safeMutex.ReleaseLock(); - clientSocket= new ClientSocket(); + clientSocket = new ClientSocket(); clientSocket->setBlock(false); clientSocket->connect(ip, port); connectedTime = time(NULL); @@ -404,23 +397,22 @@ void ClientInterface::reset() { if(getSocket() != NULL) { Lang &lang= Lang::getInstance(); const vector languageList = this->gameSettings.getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { + for(unsigned int langIndex = 0; langIndex < languageList.size(); ++langIndex) { + string sQuitText = "has chosen to leave the game!"; - if(lang.hasString("PlayerLeftGame",languageList[i]) == true) { - sQuitText = lang.getString("PlayerLeftGame",languageList[i]); + if(lang.hasString("PlayerLeftGame",languageList[langIndex]) == true) { + sQuitText = lang.getString("PlayerLeftGame",languageList[langIndex]); } - sendTextMessage(sQuitText,-1,false,languageList[i]); + sendTextMessage(sQuitText,-1,false,languageList[langIndex]); } close(); } } void ClientInterface::update() { - Chrono chrono; - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start(); - bool wasConnected = this->isConnected(); - if(gotIntro == true && wasConnected == false) { + if(gotIntro == true && + wasConnected == false) { string playerNameStr = getHumanPlayerName(); Lang &lang= Lang::getInstance(); @@ -429,7 +421,6 @@ void ClientInterface::update() { string statusTextFormat= lang.getString("PlayerDisconnected"); snprintf(szBuf1,8096,statusTextFormat.c_str(),playerNameStr.c_str()); - //string sErr = "Disconnected from server during intro handshake."; DisplayErrorMessage(szBuf1); setQuit(true); return; @@ -452,9 +443,6 @@ void ClientInterface::update() { } double lastSendElapsed = difftime((long int)time(NULL),lastNetworkCommandListSendTime); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - //printf("#1 Client send currentFrameCount = %d lastSendElapsed = %f\n",currentFrameCount,lastSendElapsed); // If we are on a frame that should send packets or we have commands @@ -464,9 +452,8 @@ void ClientInterface::update() { networkMessageCommandList.getCommandCount() > 0) { //printf("#2 Client send currentFrameCount = %d lastSendElapsed = %f\n",currentFrameCount,lastSendElapsed); - if(lastSentFrameCount < currentFrameCount || - networkMessageCommandList.getCommandCount() > 0) { + networkMessageCommandList.getCommandCount() > 0) { //printf("#3 Client send currentFrameCount = %d lastSentFrameCount = %d\n",currentFrameCount,lastSentFrameCount ); lastSentFrameCount = currentFrameCount; @@ -474,34 +461,26 @@ void ClientInterface::update() { lastNetworkCommandListSendTime = time(NULL); lastSendElapsed = difftime((long int)time(NULL),lastNetworkCommandListSendTime); } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); } + // If we have not sent anything for maxNetworkCommandListSendTimeWait // seconds, send one now. if(lastNetworkCommandListSendTime > 0 && - lastSendElapsed >= ClientInterface::maxNetworkCommandListSendTimeWait) { - //printf("#4 Client send currentFrameCount = %d lastSendElapsed = %f\n",currentFrameCount,lastSendElapsed); + lastSendElapsed >= ClientInterface::maxNetworkCommandListSendTimeWait) { lastSentFrameCount = currentFrameCount; sendMessage(&networkMessageCommandList); lastNetworkCommandListSendTime = time(NULL); - //lastSendElapsed = difftime((long int)time(NULL),lastNetworkCommandListSendTime); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); } // Possible cause of out of synch since we have more commands that need // to be sent in this frame if(requestedCommands.empty() == false) { - //char szBuf[4096]=""; if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] WARNING / ERROR, requestedCommands.size() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,requestedCommands.size()); string sMsg = "may go out of synch: client requestedCommands.size() = " + intToStr(requestedCommands.size()); sendTextMessage(sMsg,-1, true,""); sleep(1); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); } } catch(const megaglest_runtime_error &ex) { @@ -520,8 +499,6 @@ void ClientInterface::update() { throw megaglest_runtime_error(ex.what()); } } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); } std::string ClientInterface::getServerIpAddress() { @@ -539,18 +516,22 @@ void ClientInterface::updateLobby() { { NetworkMessageIntro networkMessageIntro; if(receiveMessage(&networkMessageIntro)) { - gotIntro = true; - sessionKey = networkMessageIntro.getSessionId(); - versionString = networkMessageIntro.getVersionString(); - playerIndex= networkMessageIntro.getPlayerIndex(); - serverName= networkMessageIntro.getName(); - serverUUID = networkMessageIntro.getPlayerUUID(); - serverPlatform = networkMessageIntro.getPlayerPlatform(); - serverFTPPort = networkMessageIntro.getFtpPort(); + gotIntro = true; + sessionKey = networkMessageIntro.getSessionId(); + versionString = networkMessageIntro.getVersionString(); + playerIndex = networkMessageIntro.getPlayerIndex(); + serverName = networkMessageIntro.getName(); + serverUUID = networkMessageIntro.getPlayerUUID(); + serverPlatform = networkMessageIntro.getPlayerPlatform(); + serverFTPPort = networkMessageIntro.getFtpPort(); + + if(playerIndex < 0 || playerIndex >= GameConstants::maxPlayers) { + throw megaglest_runtime_error("playerIndex < 0 || playerIndex >= GameConstants::maxPlayers"); + } MutexSafeWrapper safeMutexFlags(flagAccessor,CODE_AT_LINE); - this->joinGameInProgress = (networkMessageIntro.getGameInProgress() != 0); - this->joinGameInProgressLaunch = false; + this->joinGameInProgress = (networkMessageIntro.getGameInProgress() != 0); + this->joinGameInProgressLaunch = false; safeMutexFlags.ReleaseLock(); //printf("Client got intro playerIndex = %d\n",playerIndex); @@ -563,12 +544,11 @@ void ClientInterface::updateLobby() { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] got NetworkMessageIntro, networkMessageIntro.getGameState() = %d, versionString [%s], sessionKey = %d, playerIndex = %d, serverFTPPort = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageIntro.getGameState(),versionString.c_str(),sessionKey,playerIndex,serverFTPPort); if(compatible == false) { - //if(networkMessageIntro.getVersionString() != getNetworkVersionString()) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - bool versionMatched = false; - string platformFreeVersion = getNetworkPlatformFreeVersionString(); - string sErr = ""; + bool versionMatched = false; + string platformFreeVersion = getNetworkPlatformFreeVersionString(); + string sErr = ""; if(strncmp(platformFreeVersion.c_str(),networkMessageIntro.getVersionString().c_str(),strlen(platformFreeVersion.c_str())) != 0) { string playerNameStr = getHumanPlayerName(); @@ -582,16 +562,17 @@ void ClientInterface::updateLobby() { sendTextMessage(" Client player [" + playerNameStr + "]",-1, true,""); } else { - versionMatched = true; - - string playerNameStr = getHumanPlayerName(); + versionMatched = true; + string playerNameStr = getHumanPlayerName(); sErr = "Warning, Server and client are using the same version but different platforms.\n\nServer: " + networkMessageIntro.getVersionString() + "\nClient: " + getNetworkVersionGITString() + " player [" + playerNameStr + "]"; //printf("%s\n",sErr.c_str()); } + // error message and disconnect only if checked if(Config::getInstance().getBool("PlatformConsistencyChecks","true") && - versionMatched == false) { // error message and disconnect only if checked + versionMatched == false) { + DisplayErrorMessage(sErr); sleep(1); @@ -625,7 +606,9 @@ void ClientInterface::updateLobby() { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if(clientSocket == NULL || clientSocket->isConnected() == false) { + if(clientSocket == NULL || + clientSocket->isConnected() == false) { + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); string sErr = "Disconnected from server during intro handshake."; @@ -639,8 +622,7 @@ void ClientInterface::updateLobby() { else { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - assert(playerIndex>=0 && playerIndexsetNetworkGameDataSynchCheckTechMismatchReport(""); this->setReceivedDataSynchCheck(false); - uint32 tilesetCRC = 0; - uint32 techCRC = 0; - uint32 mapCRC = 0; + uint32 tilesetCRC = 0; + uint32 techCRC = 0; + uint32 mapCRC = 0; vector > vctFileList; try { Config &config = Config::getInstance(); string scenarioDir = ""; if(gameSettings.getScenarioDir() != "") { + scenarioDir = gameSettings.getScenarioDir(); if(EndsWith(scenarioDir, ".xml") == true) { scenarioDir = scenarioDir.erase(scenarioDir.size() - 4, 4); @@ -712,10 +695,8 @@ void ClientInterface::updateLobby() { tilesetCRC = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTilesets,scenarioDir), string("/") + networkMessageSynchNetworkGameData.getTileset() + string("/*"), ".xml", NULL); this->setNetworkGameDataSynchCheckOkTile((tilesetCRC == networkMessageSynchNetworkGameData.getTilesetCRC())); - //if(this->getNetworkGameDataSynchCheckOkTile() == false) - //{ + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] tilesetCRC info, local = %d, remote = %d, networkMessageSynchNetworkGameData.getTileset() = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,tilesetCRC,networkMessageSynchNetworkGameData.getTilesetCRC(),networkMessageSynchNetworkGameData.getTileset().c_str()); - //} //tech, load before map because of resources techCRC = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,scenarioDir), string("/") + networkMessageSynchNetworkGameData.getTech() + string("/*"), ".xml", NULL); @@ -723,6 +704,7 @@ void ClientInterface::updateLobby() { this->setNetworkGameDataSynchCheckOkTech((techCRC == networkMessageSynchNetworkGameData.getTechCRC())); if(this->getNetworkGameDataSynchCheckOkTech() == false) { + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); string pathSearchString = "/" + networkMessageSynchNetworkGameData.getTech() + "/*"; @@ -734,10 +716,7 @@ void ClientInterface::updateLobby() { this->setNetworkGameDataSynchCheckTechMismatchReport(report); } - //if(this->getNetworkGameDataSynchCheckOkTech() == false) - //{ if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] techCRC info, local = %d, remote = %d, networkMessageSynchNetworkGameData.getTech() = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,techCRC,networkMessageSynchNetworkGameData.getTechCRC(),networkMessageSynchNetworkGameData.getTech().c_str()); - //} //map Checksum checksum; @@ -749,10 +728,7 @@ void ClientInterface::updateLobby() { this->setNetworkGameDataSynchCheckOkMap((mapCRC == networkMessageSynchNetworkGameData.getMapCRC())); this->setReceivedDataSynchCheck(true); - //if(this->getNetworkGameDataSynchCheckOkMap() == false) - //{ if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] mapCRC info, local = %d, remote = %d, file = [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,mapCRC,networkMessageSynchNetworkGameData.getMapCRC(),file.c_str()); - //} } catch(const runtime_error &ex) { SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); @@ -771,8 +747,7 @@ void ClientInterface::updateLobby() { case nmtSynchNetworkGameDataFileCRCCheck: { NetworkMessageSynchNetworkGameDataFileCRCCheck networkMessageSynchNetworkGameDataFileCRCCheck; - if(receiveMessage(&networkMessageSynchNetworkGameDataFileCRCCheck)) - { + if(receiveMessage(&networkMessageSynchNetworkGameDataFileCRCCheck)) { this->setLastPingInfoToNow(); Checksum checksum; @@ -780,8 +755,7 @@ void ClientInterface::updateLobby() { checksum.addFile(file); uint32 fileCRC = checksum.getSum(); - if(fileCRC != networkMessageSynchNetworkGameDataFileCRCCheck.getFileCRC()) - { + if(fileCRC != networkMessageSynchNetworkGameDataFileCRCCheck.getFileCRC()) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] got nmtSynchNetworkGameDataFileCRCCheck localCRC = %d, remoteCRC = %d, file [%s]\n", extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,fileCRC, networkMessageSynchNetworkGameDataFileCRCCheck.getFileCRC(), @@ -818,8 +792,7 @@ void ClientInterface::updateLobby() { case nmtText: { NetworkMessageText networkMessageText; - if(receiveMessage(&networkMessageText)) - { + if(receiveMessage(&networkMessageText)) { this->setLastPingInfoToNow(); if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] got nmtText\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); @@ -902,30 +875,30 @@ void ClientInterface::updateLobby() { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Lined: %d] got networkMessageLaunch.getMessageType() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageLaunch.getMessageType()); //replace server player by network - for(int i= 0; i 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] receiveMessage took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start(); - MutexSafeWrapper safeMutex(networkCommandListThreadAccessor,CODE_AT_LINE); cachedLastPendingFrameCount = networkMessageCommandList.getFrameCount(); //printf("cachedLastPendingFrameCount = %lld\n",(long long int)cachedLastPendingFrameCount); @@ -1140,9 +1106,7 @@ void ClientInterface::updateFrame(int *checkFrame) { } safeMutex.ReleaseLock(); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] transfer network commands took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - - done= true; + done = true; } break; @@ -1155,19 +1119,12 @@ void ClientInterface::updateFrame(int *checkFrame) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); this->setLastPingInfo(networkMessagePing); } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); } break; case nmtQuit: { - //time_t receiveTimeElapsed = time(NULL); NetworkMessageQuit networkMessageQuit; - // while(receiveMessage(&networkMessageQuit) == false && - // isConnected() == true && - // difftime(time(NULL),receiveTimeElapsed) <= (messageWaitTimeout / 2000)) { - // } bool gotCmd = receiveMessage(&networkMessageQuit); if(gotCmd == false) { SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] error retrieving nmtQuit returned false!\n",__FILE__,__FUNCTION__,__LINE__); @@ -1180,18 +1137,19 @@ void ClientInterface::updateFrame(int *checkFrame) { throw megaglest_runtime_error("error retrieving nmtQuit returned false!"); } setQuit(true); - done= true; + done = true; } break; case nmtText: { - //time_t receiveTimeElapsed = time(NULL); NetworkMessageText networkMessageText; bool gotCmd = receiveMessage(&networkMessageText); if(gotCmd == false) { + SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] error retrieving nmtText returned false!\n",__FILE__,__FUNCTION__,__LINE__); if(isConnected() == false) { + setQuit(true); close(); return; @@ -1199,12 +1157,9 @@ void ClientInterface::updateFrame(int *checkFrame) { throw megaglest_runtime_error("error retrieving nmtText returned false!"); } - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); ChatMsgInfo msg(networkMessageText.getText().c_str(),networkMessageText.getTeamIndex(),networkMessageText.getPlayerIndex(),networkMessageText.getTargetLanguage()); this->addChatInfo(msg); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); } break; @@ -1292,13 +1247,6 @@ void ClientInterface::updateFrame(int *checkFrame) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] gameSettings.getThisFactionIndex(i) = %d, playerIndex = %d, i = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,gameSettings.getThisFactionIndex(),playerIndex,i); } } - - //if(networkMessageLaunch.getMessageType() == nmtLaunch) { - //launchGame= true; - //} - //else if(networkMessageLaunch.getMessageType() == nmtBroadCastSetup) { - // setGameSettingsReceived(true); - //} } } break; @@ -1318,7 +1266,7 @@ void ClientInterface::updateFrame(int *checkFrame) { setQuit(true); close(); - done= true; + done = true; } break; } @@ -1326,10 +1274,6 @@ void ClientInterface::updateFrame(int *checkFrame) { if(isConnected() == false && getQuit() == true) { done = true; } - // Sleep ever second we wait to let other threads work -// else if(chrono.getMillis() % 25 == 0) { -// sleep(1); -// } if(debugClientInterfacePerf == true) { loopCount++; @@ -1347,10 +1291,6 @@ void ClientInterface::updateFrame(int *checkFrame) { MutexSafeWrapper safeMutex(networkCommandListThreadAccessor,CODE_AT_LINE); cachedPendingCommandsIndex++; } - else if(checkFrame == NULL) { - //sleep(15); - //sleep(0); - } } //printf("#3 ClientInterface::updateFrame\n"); } @@ -1358,53 +1298,30 @@ void ClientInterface::updateFrame(int *checkFrame) { uint64 ClientInterface::getCachedLastPendingFrameCount() { MutexSafeWrapper safeMutex(networkCommandListThreadAccessor,CODE_AT_LINE); uint64 result = cachedLastPendingFrameCount; - safeMutex.ReleaseLock(); - return result; } int64 ClientInterface::getTimeClientWaitedForLastMessage() { MutexSafeWrapper safeMutex(networkCommandListThreadAccessor,CODE_AT_LINE); uint64 result = timeClientWaitedForLastMessage; - safeMutex.ReleaseLock(); - return result; } - - -//void ClientInterface::simpleTask(BaseThread *callingThread) { -// Chrono chrono; -// if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start(); -// -// //printf("START === Client thread ended\n"); -// -// while(callingThread->getQuitStatus() == false && this->quitThread == false) { -// updateFrame(NULL); -// } -// -// //printf("END === Client thread ended\n"); -// -// if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); -//} - bool ClientInterface::getNetworkCommand(int frameCount, int currentCachedPendingCommandsIndex) { - bool result = false; - - bool waitForData = false; - uint64 copyCachedLastPendingFrameCount = 0; - uint64 waitCount = 0; - Chrono chrono; - timeClientWaitedForLastMessage = 0; + bool result = false; + bool waitForData = false; + uint64 copyCachedLastPendingFrameCount = 0; + uint64 waitCount = 0; + uint64 frameCountAsUInt64 = frameCount; + timeClientWaitedForLastMessage = 0; if(getQuit() == false && getQuitThread() == false) { - //MutexSafeWrapper safeMutex(networkCommandListThreadAccessor,CODE_AT_LINE); - //safeMutex.ReleaseLock(true); + + Chrono chrono; MutexSafeWrapper safeMutex(NULL,CODE_AT_LINE); for(;getQuit() == false && getQuitThread() == false;) { - //MutexSafeWrapper safeMutex(networkCommandListThreadAccessor,CODE_AT_LINE); - //safeMutex.Lock(); + if(safeMutex.isValidMutex() == false) { safeMutex.setMutex(networkCommandListThreadAccessor,CODE_AT_LINE); } @@ -1412,13 +1329,14 @@ bool ClientInterface::getNetworkCommand(int frameCount, int currentCachedPending safeMutex.Lock(); } copyCachedLastPendingFrameCount = cachedLastPendingFrameCount; + if(cachedPendingCommands.find(frameCount) != cachedPendingCommands.end()) { + Commands &frameCmdList = cachedPendingCommands[frameCount]; - if(frameCmdList.size() > 0) { - for(int i= 0; i < (int)frameCmdList.size(); ++i) { - pendingCommands.push_back(frameCmdList[i]); + if(frameCmdList.empty() == false) { + for(int index = 0; index < (int)frameCmdList.size(); ++index) { + pendingCommands.push_back(frameCmdList[index]); } - //cachedPendingCommands.erase(frameCount); cachedPendingCommands[frameCount].clear(); if(frameCount >= 0) { @@ -1439,14 +1357,13 @@ bool ClientInterface::getNetworkCommand(int frameCount, int currentCachedPending setQuit(true); close(); - //return; } } } cachedPendingCommandCRCs.erase(frameCount); } if(waitForData == true) { - timeClientWaitedForLastMessage=chrono.getMillis(); + timeClientWaitedForLastMessage = chrono.getMillis(); chrono.stop(); } safeMutex.ReleaseLock(true); @@ -1457,15 +1374,11 @@ bool ClientInterface::getNetworkCommand(int frameCount, int currentCachedPending else { safeMutex.ReleaseLock(true); // No data for this frame - //if(cachedPendingCommandsIndex > currentCachedPendingCommandsIndex) { - // break; - //} - if(waitForData == false) { if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Client waiting for packet for frame: %d, copyCachedLastPendingFrameCount = %lld\n",frameCount,(long long int)copyCachedLastPendingFrameCount); chrono.start(); } - if(copyCachedLastPendingFrameCount > (uint64)frameCount) { + if(copyCachedLastPendingFrameCount > frameCountAsUInt64) { break; } @@ -1475,7 +1388,6 @@ bool ClientInterface::getNetworkCommand(int frameCount, int currentCachedPending } waitCount++; - //printf("Client waiting for packet for frame: %d, currentCachedPendingCommandsIndex = %d, cachedPendingCommandsIndex = %lld\n",frameCount,currentCachedPendingCommandsIndex,(long long int)cachedPendingCommandsIndex); } } @@ -1490,40 +1402,18 @@ bool ClientInterface::getNetworkCommand(int frameCount, int currentCachedPending void ClientInterface::updateKeyframe(int frameCount) { currentFrameCount = frameCount; - Chrono chrono; - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start(); - //chrono.start(); - if(getQuit() == false && getQuitThread() == false) { - //bool testThreaded = Config::getInstance().getBool("ThreadedNetworkClient","true"); -// bool testThreaded = true; -// if(testThreaded == false) { -// updateFrame(&frameCount); -// Commands &frameCmdList = cachedPendingCommands[frameCount]; -// for(int i= 0; i < (int)frameCmdList.size(); ++i) { -// pendingCommands.push_back(frameCmdList[i]); -// } -// cachedPendingCommands.erase(frameCount); -// } -// else { - if(networkCommandListThread == NULL) { - static string mutexOwnerId = string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + intToStr(__LINE__); -// networkCommandListThread = new SimpleTaskThread(this,0,0); -// networkCommandListThread->setUniqueID(mutexOwnerId); -// networkCommandListThread->start(); - networkCommandListThread = new ClientInterfaceThread(this); - networkCommandListThread->setUniqueID(mutexOwnerId); - networkCommandListThread->start(); + if(networkCommandListThread == NULL) { + static string mutexOwnerId = string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + intToStr(__LINE__); + networkCommandListThread = new ClientInterfaceThread(this); + networkCommandListThread->setUniqueID(mutexOwnerId); + networkCommandListThread->start(); - sleep(0); - } + sleep(0); + } - getNetworkCommand(frameCount,cachedPendingCommandsIndex); - //} + getNetworkCommand(frameCount,cachedPendingCommandsIndex); } - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - //printf("In [%s::%s Line: %d] took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); } bool ClientInterface::isMasterServerAdminOverride() { @@ -1535,7 +1425,7 @@ void ClientInterface::waitUntilReady(Checksum* checksum) { MutexSafeWrapper safeMutexFlags(flagAccessor,CODE_AT_LINE); bool signalServerWhenReadyToStartJoinedGame = this->readyForInGameJoin; - this->readyForInGameJoin = false; + this->readyForInGameJoin = false; safeMutexFlags.ReleaseLock(); Logger &logger= Logger::getInstance(); @@ -1556,11 +1446,11 @@ void ClientInterface::waitUntilReady(Checksum* checksum) { NetworkMessageLoadingStatus networkMessageLoadingStatus(nmls_NONE); Lang &lang= Lang::getInstance(); - int64 lastMillisCheck = 0; - uint64 waitLoopIterationCount = 0; - uint64 MAX_LOOP_COUNT_BEFORE_SLEEP = 100; - MAX_LOOP_COUNT_BEFORE_SLEEP = Config::getInstance().getInt("NetworkClientLoopGameLoadingCap",intToStr(MAX_LOOP_COUNT_BEFORE_SLEEP).c_str()); + int64 lastMillisCheck = 0; + uint64 waitLoopIterationCount = 0; + uint64 MAX_LOOP_COUNT_BEFORE_SLEEP = 100; + MAX_LOOP_COUNT_BEFORE_SLEEP = Config::getInstance().getInt("NetworkClientLoopGameLoadingCap",intToStr(MAX_LOOP_COUNT_BEFORE_SLEEP).c_str()); if(MAX_LOOP_COUNT_BEFORE_SLEEP == 0) { MAX_LOOP_COUNT_BEFORE_SLEEP = 1; } @@ -1572,7 +1462,8 @@ void ClientInterface::waitUntilReady(Checksum* checksum) { //sleep(2000); waitLoopIterationCount++; - if(waitLoopIterationCount > 0 && waitLoopIterationCount % MAX_LOOP_COUNT_BEFORE_SLEEP == 0) { + if(waitLoopIterationCount > 0 && + waitLoopIterationCount % MAX_LOOP_COUNT_BEFORE_SLEEP == 0) { sleep(sleepMillis); waitLoopIterationCount = 0; } @@ -1625,9 +1516,7 @@ void ClientInterface::waitUntilReady(Checksum* checksum) { } } else if(networkMessageType == nmtCommandList) { - //int waitCount = 0; //make sure we read the message - //time_t receiveTimeElapsed = time(NULL); NetworkMessageCommandList networkMessageCommandList; bool gotCmd = receiveMessage(&networkMessageCommandList); if(gotCmd == false) { @@ -1663,7 +1552,6 @@ void ClientInterface::waitUntilReady(Checksum* checksum) { return; } else { - //if(chrono.getMillis() / 1000 > lastMillisCheck) { if(chrono.getMillis() % 100 == 0) { lastMillisCheck = (chrono.getMillis() / 1000); @@ -1784,37 +1672,40 @@ void ClientInterface::waitUntilReady(Checksum* checksum) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); //check checksum - if(getJoinGameInProgress() == false && networkMessageReady.getChecksum() != checksum->getSum()) { + if(getJoinGameInProgress() == false && + networkMessageReady.getChecksum() != checksum->getSum()) { + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); Lang &lang= Lang::getInstance(); const vector languageList = this->gameSettings.getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { + for(unsigned int langIndex = 0; langIndex < languageList.size(); ++langIndex) { + string sErr = "Checksum error, you don't have the same data as the server"; - if(lang.hasString("CheckSumGameLoadError",languageList[i]) == true) { - sErr = lang.getString("CheckSumGameLoadError",languageList[i]); + if(lang.hasString("CheckSumGameLoadError",languageList[langIndex]) == true) { + sErr = lang.getString("CheckSumGameLoadError",languageList[langIndex]); } bool echoLocal = lang.isLanguageLocal(lang.getLanguage()); - sendTextMessage(sErr,-1,echoLocal,languageList[i]); + sendTextMessage(sErr,-1,echoLocal,languageList[langIndex]); string playerNameStr = "Player with error is: " + getHumanPlayerName(); - if(lang.hasString("CheckSumGameLoadPlayer",languageList[i]) == true) { - playerNameStr = lang.getString("CheckSumGameLoadPlayer",languageList[i]) + " " + getHumanPlayerName(); + if(lang.hasString("CheckSumGameLoadPlayer",languageList[langIndex]) == true) { + playerNameStr = lang.getString("CheckSumGameLoadPlayer",languageList[langIndex]) + " " + getHumanPlayerName(); } - sendTextMessage(playerNameStr,-1,echoLocal,languageList[i]); + sendTextMessage(playerNameStr,-1,echoLocal,languageList[langIndex]); string sErr1 = "Client Checksum: " + intToStr(checksum->getSum()); - if(lang.hasString("CheckSumGameLoadClient",languageList[i]) == true) { - sErr1 = lang.getString("CheckSumGameLoadClient",languageList[i]) + " " + intToStr(checksum->getSum()); + if(lang.hasString("CheckSumGameLoadClient",languageList[langIndex]) == true) { + sErr1 = lang.getString("CheckSumGameLoadClient",languageList[langIndex]) + " " + intToStr(checksum->getSum()); } - sendTextMessage(sErr1,-1,echoLocal,languageList[i]); + sendTextMessage(sErr1,-1,echoLocal,languageList[langIndex]); string sErr2 = "Server Checksum: " + intToStr(networkMessageReady.getChecksum()); - if(lang.hasString("CheckSumGameLoadServer",languageList[i]) == true) { - sErr2 = lang.getString("CheckSumGameLoadServer",languageList[i]) + " " + intToStr(networkMessageReady.getChecksum()); + if(lang.hasString("CheckSumGameLoadServer",languageList[langIndex]) == true) { + sErr2 = lang.getString("CheckSumGameLoadServer",languageList[langIndex]) + " " + intToStr(networkMessageReady.getChecksum()); } - sendTextMessage(sErr2,-1,echoLocal,languageList[i]); + sendTextMessage(sErr2,-1,echoLocal,languageList[langIndex]); if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d %s %s %s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,sErr.c_str(),sErr1.c_str(),sErr2.c_str()); @@ -1829,28 +1720,10 @@ void ClientInterface::waitUntilReady(Checksum* checksum) { } } -// string sErr = "Checksum error, you don't have the same data as the server"; -// CheckSumGameLoadError -// sendTextMessage(sErr,-1, true); -// -// string playerNameStr = "Player with error is [" + getHumanPlayerName() + "]"; -// sendTextMessage(playerNameStr,-1, true); -// -// string sErr1 = "Client Checksum: " + intToStr(checksum->getSum()); -// sendTextMessage(sErr1,-1, true); -// -// string sErr2 = "Server Checksum: " + intToStr(networkMessageReady.getChecksum()); -// sendTextMessage(sErr2,-1, true); - -// if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d %s %s %s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,sErr.c_str(),sErr1.c_str(),sErr2.c_str()); - if(Config::getInstance().getBool("NetworkConsistencyChecks")) { // error message and disconnect only if checked if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - //string niceError = sErr + string("\n") + sErr1 + string("\n") + sErr2; - //DisplayErrorMessage(niceError); - sleep(1); setQuit(true); @@ -1862,17 +1735,19 @@ void ClientInterface::waitUntilReady(Checksum* checksum) { } MutexSafeWrapper safeMutexFlags2(flagAccessor,CODE_AT_LINE); - this->joinGameInProgress = false; - this->joinGameInProgressLaunch = false; + this->joinGameInProgress = false; + this->joinGameInProgressLaunch = false; //printf("Client signalServerWhenReadyToStartJoinedGame = %d\n",signalServerWhenReadyToStartJoinedGame); if(signalServerWhenReadyToStartJoinedGame == true) { + Lang &lang= Lang::getInstance(); const vector languageList = this->gameSettings.getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { + for(unsigned int langIndex = 0; langIndex < languageList.size(); ++langIndex) { + string sText = "Player: %s is joining the game now."; - if(lang.hasString("JoinPlayerToCurrentGameLaunchDone",languageList[i]) == true) { - sText = lang.getString("JoinPlayerToCurrentGameLaunchDone",languageList[i]); + if(lang.hasString("JoinPlayerToCurrentGameLaunchDone",languageList[langIndex]) == true) { + sText = lang.getString("JoinPlayerToCurrentGameLaunchDone",languageList[langIndex]); } if(clientSocket != NULL && clientSocket->isConnected() == true) { @@ -1880,7 +1755,7 @@ void ClientInterface::waitUntilReady(Checksum* checksum) { char szBuf[8096]=""; snprintf(szBuf,8096,sText.c_str(),playerNameStr.c_str()); - sendTextMessage(szBuf,-1,false,languageList[i]); + sendTextMessage(szBuf,-1,false,languageList[langIndex]); } } @@ -1979,8 +1854,9 @@ NetworkMessageType ClientInterface::waitForMessage(int waitMicroseconds) chrono.start(); NetworkMessageType msg = nmtInvalid; - //uint64 waitLoopCount = 0; - while(msg == nmtInvalid && getQuitThread() == false) { + while( msg == nmtInvalid && + getQuitThread() == false) { + msg = getNextMessageType(waitMicroseconds); if(msg == nmtInvalid) { if(chrono.getMillis() % 250 == 0 && isConnected() == false) { @@ -1995,24 +1871,23 @@ NetworkMessageType ClientInterface::waitForMessage(int waitMicroseconds) } if(chrono.getMillis() > messageWaitTimeout) { - //if(1) { - //throw megaglest_runtime_error("Timeout waiting for message"); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); Lang &lang= Lang::getInstance(); const vector languageList = this->gameSettings.getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { + for(unsigned int langIndex = 0; langIndex < languageList.size(); ++langIndex) { + string msg = "Timeout waiting for message."; - if(lang.hasString("TimeoutWaitingForMessage",languageList[i]) == true) { - msg = lang.getString("TimeoutWaitingForMessage",languageList[i]); + if(lang.hasString("TimeoutWaitingForMessage",languageList[langIndex]) == true) { + msg = lang.getString("TimeoutWaitingForMessage",languageList[langIndex]); } - sendTextMessage(msg,-1, lang.isLanguageLocal(languageList[i]),languageList[i]); - if(lang.isLanguageLocal(languageList[i]) == true) { + sendTextMessage(msg,-1, lang.isLanguageLocal(languageList[langIndex]),languageList[langIndex]); + if(lang.isLanguageLocal(languageList[langIndex]) == true) { DisplayErrorMessage(msg); } } + sleep(1); setQuit(true); close(); @@ -2022,10 +1897,7 @@ NetworkMessageType ClientInterface::waitForMessage(int waitMicroseconds) else if(chrono.getMillis() % 20 == 0) { sleep(5); } - - //sleep(waitSleepTime); } - //waitLoopCount++; if(debugClientInterfacePerf == true) { loopCount++; @@ -2033,13 +1905,11 @@ NetworkMessageType ClientInterface::waitForMessage(int waitMicroseconds) printf("Client waitForMessage loopCount = %llu\n",(long long unsigned int)loopCount); loopCount = 0; - //sleep(0); chronoPerf.start(); } } } - //if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] waiting took %lld msecs, waitLoopCount = %ull, msg = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis(),waitLoopCount,msg); if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] waiting took %lld msecs, msg = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis(),msg); return msg; @@ -2049,19 +1919,19 @@ void ClientInterface::quitGame(bool userManuallyQuit) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] userManuallyQuit = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,userManuallyQuit); - if(clientSocket != NULL && userManuallyQuit == true) - { + if(clientSocket != NULL && userManuallyQuit == true) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); Lang &lang= Lang::getInstance(); const vector languageList = this->gameSettings.getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { + for(unsigned int langIndex = 0; langIndex < languageList.size(); ++langIndex) { + string msg = "has chosen to leave the game!"; - if(lang.hasString("PlayerLeftGame",languageList[i]) == true) { - msg = lang.getString("PlayerLeftGame",languageList[i]); + if(lang.hasString("PlayerLeftGame",languageList[langIndex]) == true) { + msg = lang.getString("PlayerLeftGame",languageList[langIndex]); } - sendTextMessage(msg,-1, lang.isLanguageLocal(languageList[i]),languageList[i]); + sendTextMessage(msg,-1, lang.isLanguageLocal(languageList[langIndex]),languageList[langIndex]); } sleep(1); close(); @@ -2080,7 +1950,7 @@ void ClientInterface::close(bool lockMutex) { shutdownNetworkCommandListThread(safeMutex); delete clientSocket; - clientSocket= NULL; + clientSocket = NULL; safeMutex.ReleaseLock(); @@ -2088,9 +1958,9 @@ void ClientInterface::close(bool lockMutex) { gotIntro = false; MutexSafeWrapper safeMutexFlags(flagAccessor,CODE_AT_LINE); - this->joinGameInProgress = false; - this->joinGameInProgressLaunch = false; - this->readyForInGameJoin = false; + this->joinGameInProgress = false; + this->joinGameInProgressLaunch = false; + this->readyForInGameJoin = false; if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] END\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); } @@ -2119,9 +1989,9 @@ void ClientInterface::sendSwitchSetupRequest(string selectedFactionName, int8 cu int8 networkPlayerStatus, int8 flags, string language) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] networkPlayerName [%s] flags = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkPlayerName.c_str(),flags); - SwitchSetupRequest message=SwitchSetupRequest(selectedFactionName, - currentSlotIndex, toSlotIndex,toTeam,networkPlayerName, - networkPlayerStatus, flags,language); + SwitchSetupRequest message = SwitchSetupRequest(selectedFactionName, + currentSlotIndex, toSlotIndex,toTeam,networkPlayerName, + networkPlayerStatus, flags,language); sendMessage(&message); if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); } @@ -2261,8 +2131,6 @@ bool ClientInterface::shouldDiscardNetworkMessage(NetworkMessageType networkMess string ClientInterface::getHumanPlayerName(int index) { string result = Config::getInstance().getString("NetPlayerName",Socket::getHostName().c_str()); - //printf("Client getHumanPlayerName index = %d, gameSettings.getThisFactionIndex() = %d\n",index,gameSettings.getThisFactionIndex()); - if(index >= 0 || gameSettings.getThisFactionIndex() >= 0) { if(index < 0) { index = gameSettings.getThisFactionIndex(); @@ -2275,20 +2143,20 @@ string ClientInterface::getHumanPlayerName(int index) { return result; } - void ClientInterface::setGameSettings(GameSettings *serverGameSettings) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] START\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); - //MutexSafeWrapper safeMutex(&serverSynchAccessor,string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + intToStr(__LINE__)); + gameSettings = *serverGameSettings; + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] END\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); } void ClientInterface::broadcastGameSetup(const GameSettings *gameSettings) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - //MutexSafeWrapper safeMutex(&serverSynchAccessor,string(extractFileFromDirectoryPath(__FILE__).c_str()) + "_" + intToStr(__LINE__)); + NetworkMessageLaunch networkMessageLaunch(gameSettings, nmtBroadCastSetup); - //broadcastMessage(&networkMessageLaunch); sendMessage(&networkMessageLaunch); + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); } diff --git a/source/glest_game/network/connection_slot.cpp b/source/glest_game/network/connection_slot.cpp index 6dd6260f9..cec0f5b05 100644 --- a/source/glest_game/network/connection_slot.cpp +++ b/source/glest_game/network/connection_slot.cpp @@ -31,30 +31,28 @@ namespace Glest{ namespace Game{ // ===================================================== ConnectionSlotThread::ConnectionSlotThread(int slotIndex) : BaseThread() { - this->masterController = NULL; - this->triggerIdMutex = new Mutex(); - this->slotIndex = slotIndex; - this->slotInterface = NULL; - uniqueID = "ConnectionSlotThread"; - //this->event = NULL; + this->masterController = NULL; + this->triggerIdMutex = new Mutex(); + this->slotIndex = slotIndex; + this->slotInterface = NULL; + uniqueID = "ConnectionSlotThread"; eventList.clear(); - eventList.reserve(100); + eventList.reserve(1000); - triggerGameStarted = new Mutex(); - gameStarted = false; + triggerGameStarted = new Mutex(); + gameStarted = false; } ConnectionSlotThread::ConnectionSlotThread(ConnectionSlotCallbackInterface *slotInterface,int slotIndex) : BaseThread() { - this->masterController = NULL; - this->triggerIdMutex = new Mutex(); - this->slotIndex = slotIndex; - this->slotInterface = slotInterface; - uniqueID = "ConnectionSlotThread"; - //this->event = NULL; + this->masterController = NULL; + this->triggerIdMutex = new Mutex(); + this->slotIndex = slotIndex; + this->slotInterface = slotInterface; + uniqueID = "ConnectionSlotThread"; eventList.clear(); - triggerGameStarted = new Mutex(); - gameStarted = false; + triggerGameStarted = new Mutex(); + gameStarted = false; } ConnectionSlotThread::~ConnectionSlotThread() { @@ -80,7 +78,6 @@ void ConnectionSlotThread::signalUpdate(ConnectionSlotEvent *event) { if(event != NULL) { MutexSafeWrapper safeMutex(triggerIdMutex,CODE_AT_LINE); eventList.push_back(*event); - safeMutex.ReleaseLock(); } if(getGameStarted() == true && getQuitStatus() == true) { return; @@ -91,46 +88,39 @@ void ConnectionSlotThread::signalUpdate(ConnectionSlotEvent *event) { void ConnectionSlotThread::setTaskCompleted(int eventId) { if(eventId > 0) { MutexSafeWrapper safeMutex(triggerIdMutex,CODE_AT_LINE); - //event->eventCompleted = true; - for(int i = 0; i < (int)eventList.size(); ++i) { - ConnectionSlotEvent &slotEvent = eventList[i]; + for(int index = 0; index < (int)eventList.size(); ++index) { + ConnectionSlotEvent &slotEvent = eventList[index]; if(slotEvent.eventId == eventId) { - //eventList.erase(eventList.begin() + i); slotEvent.eventCompleted = true; break; } } - safeMutex.ReleaseLock(); } } void ConnectionSlotThread::purgeAllEvents() { MutexSafeWrapper safeMutex(triggerIdMutex,CODE_AT_LINE); eventList.clear(); - safeMutex.ReleaseLock(); } void ConnectionSlotThread::setAllEventsCompleted() { MutexSafeWrapper safeMutex(triggerIdMutex,CODE_AT_LINE); - for(int i = 0; i < (int)eventList.size(); ++i) { - ConnectionSlotEvent &slotEvent = eventList[i]; + for(int index = 0; index < (int)eventList.size(); ++index) { + ConnectionSlotEvent &slotEvent = eventList[index]; if(slotEvent.eventCompleted == false) { slotEvent.eventCompleted = true; } } - safeMutex.ReleaseLock(); } void ConnectionSlotThread::purgeCompletedEvents() { MutexSafeWrapper safeMutex(triggerIdMutex,CODE_AT_LINE); - //event->eventCompleted = true; - for(int i = (int)eventList.size() - 1; i >= 0; i--) { - ConnectionSlotEvent &slotEvent = eventList[i]; + for(int index = (int)eventList.size() - 1; index >= 0; index--) { + ConnectionSlotEvent &slotEvent = eventList[index]; if(slotEvent.eventCompleted == true) { - eventList.erase(eventList.begin() + i); + eventList.erase(eventList.begin() + index); } } - safeMutex.ReleaseLock(); } bool ConnectionSlotThread::canShutdown(bool deleteSelfIfShutdownDelayed) { @@ -145,43 +135,32 @@ bool ConnectionSlotThread::canShutdown(bool deleteSelfIfShutdownDelayed) { } bool ConnectionSlotThread::isSignalCompleted(ConnectionSlotEvent *event) { - MutexSafeWrapper safeMutex(triggerIdMutex,CODE_AT_LINE); bool result = false; if(event != NULL) { - for(int i = 0; i < (int)eventList.size(); ++i) { - ConnectionSlotEvent &slotEvent = eventList[i]; + MutexSafeWrapper safeMutex(triggerIdMutex,CODE_AT_LINE); + for(int index = 0; index < (int)eventList.size(); ++index) { + ConnectionSlotEvent &slotEvent = eventList[index]; if(slotEvent.eventId == event->eventId) { result = slotEvent.eventCompleted; break; } } } - //safeMutex.ReleaseLock(); return result; } void ConnectionSlotThread::slotUpdateTask(ConnectionSlotEvent *event) { - if(event != NULL) { + if(event != NULL && event->connectionSlot != NULL) { if(event->eventType == eSendSocketData) { - if(event->connectionSlot != NULL) { - event->connectionSlot->sendMessage(event->networkMessage); - } + event->connectionSlot->sendMessage(event->networkMessage); } else if(event->eventType == eReceiveSocketData) { - //updateSlot(event); - if(event->connectionSlot != NULL) { - event->connectionSlot->updateSlot(event); - } - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + event->connectionSlot->updateSlot(event); } } } void ConnectionSlotThread::signalSlave(void *userdata) { - - //ConnectionSlotEvent &event = eventList[i]; std::map *eventList = (std::map *)userdata; ConnectionSlotEvent &event = (*eventList)[slotIndex]; signalUpdate(&event); @@ -193,36 +172,30 @@ bool ConnectionSlotThread::getGameStarted() { } void ConnectionSlotThread::setGameStarted(bool value) { MutexSafeWrapper safeMutexGameStarted(triggerGameStarted,CODE_AT_LINE); - if(gameStarted != value) { gameStarted = value; if(gameStarted == true) { - //printf("Signal game has started for slot: %d\n",slotIndex); semTaskSignalled.signal(); } - else { - //printf("Signal game has NOT started for slot: %d\n",slotIndex); - } } } void ConnectionSlotThread::execute() { RunningStatusSafeWrapper runningStatus(this); try { - //setRunningStatus(true); if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - //printf("Starting client SLOT thread: %d\n",slotIndex); - //unsigned int idx = 0; for(;this->slotInterface != NULL;) { if(getQuitStatus() == true) { SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); break; } - if(this->slotInterface->getAllowInGameConnections() == true && + // Does this game allow joining in progress play and is this slot + // not already connected to a client? + if( this->slotInterface->getAllowInGameConnections() == true && this->slotInterface->isClientConnected(slotIndex) == false) { //printf("#1 Non connected slot: %d waiting for client connection..\n",slotIndex); sleep(100); @@ -233,37 +206,21 @@ void ConnectionSlotThread::execute() { } //printf("Slot thread slotIndex: %d eventCount: %d\n",slotIndex,eventCount); - //if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] Slot thread slotIndex: %d eventCount: %d\n",__FILE__,__FUNCTION__,__LINE__,slotIndex,eventCount); - //if(eventCount > 0) { ConnectionSlotEvent eventCopy; - eventCopy.eventType = eReceiveSocketData; - eventCopy.connectionSlot = this->slotInterface->getSlot(slotIndex); - eventCopy.eventId = -1; + eventCopy.eventType = eReceiveSocketData; + eventCopy.connectionSlot = this->slotInterface->getSlot(slotIndex); if(getQuitStatus() == true) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); break; } - //if(eventCopy.eventId > 0) { ExecutingTaskSafeWrapper safeExecutingTaskMutex(this); - - //if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] Slot thread slotIndex: %d eventCount: %d eventCopy.eventId: %d\n",__FILE__,__FUNCTION__,__LINE__,slotIndex,eventCount,(int)eventCopy.eventId); - //printf("#1 Slot thread slotIndex: %d eventCount: %d eventCopy.eventId: %d\n",slotIndex,eventCount,(int)eventCopy.eventId); - //this->slotInterface->slotUpdateTask(&eventCopy); - - //printf("#2 Non connected slot: %d waiting for client connection..\n",slotIndex); this->slotUpdateTask(&eventCopy); - //setTaskCompleted(eventCopy.eventId); - //printf("#2 Slot thread slotIndex: %d eventCount: %d eventCopy.eventId: %d\n",slotIndex,eventCount,(int)eventCopy.eventId); - //} - //} - //else { - // safeMutex.ReleaseLock(); - //} } else { + // If the game already started? if(getGameStarted() == true) { //printf("#A Checking action for slot: %d\n",slotIndex); @@ -285,54 +242,42 @@ void ConnectionSlotThread::execute() { break; } - //bool socketHasReadData = socket->hasDataToReadWithWait(1000); - //bool socketHasReadData = socket->hasDataToRead();; // Avoid mutex locking //bool socketHasReadData = Socket::hasDataToRead(socket->getSocketId()); bool socketHasReadData = Socket::hasDataToReadWithWait(socket->getSocketId(),150000); ConnectionSlotEvent eventCopy; - eventCopy.eventType = eReceiveSocketData; - eventCopy.connectionSlot = slot; - eventCopy.eventId = slotIndex; - eventCopy.socketTriggered = socketHasReadData; - //eventCopy.socketTriggered = true; + eventCopy.eventType = eReceiveSocketData; + eventCopy.connectionSlot = slot; + eventCopy.eventId = slotIndex; + eventCopy.socketTriggered = socketHasReadData; if(getQuitStatus() == true) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); break; } - //printf("#C Checking action for slot: %d\n",slotIndex); this->slotUpdateTask(&eventCopy); - //printf("#D Checking action for slot: %d\n",slotIndex); - - //if(socketHasReadData == false && getQuitStatus() == false) { - // sleep(10); - //} } + // Game has not yet started else { //printf("#1 Checking action for slot: %d\n",slotIndex); if(getGameStarted() == true) { continue; } - //printf("#2 Checking action for slot: %d\n",slotIndex); semTaskSignalled.waitTillSignalled(); - //printf("#3 Checking action for slot: %d\n",slotIndex); if(getGameStarted() == true) { continue; } - //printf("#4 Checking action for slot: %d\n",slotIndex); static string masterSlaveOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); MasterSlaveThreadControllerSafeWrapper safeMasterController(masterController,20000,masterSlaveOwnerId); - if(getQuitStatus() == true) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); break; @@ -346,8 +291,6 @@ void ConnectionSlotThread::execute() { if(eventCount > 0) { ConnectionSlotEvent eventCopy; - eventCopy.eventId = -1; - for(int i = 0; i < (int)eventList.size(); ++i) { ConnectionSlotEvent &slotEvent = eventList[i]; if(slotEvent.eventCompleted == false) { @@ -355,7 +298,6 @@ void ConnectionSlotThread::execute() { break; } } - safeMutex.ReleaseLock(); if(getQuitStatus() == true) { @@ -368,15 +310,13 @@ void ConnectionSlotThread::execute() { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] Slot thread slotIndex: %d eventCount: %d eventCopy.eventId: %d\n",__FILE__,__FUNCTION__,__LINE__,slotIndex,eventCount,(int)eventCopy.eventId); //printf("#1 Slot thread slotIndex: %d eventCount: %d eventCopy.eventId: %d\n",slotIndex,eventCount,(int)eventCopy.eventId); - //this->slotInterface->slotUpdateTask(&eventCopy); + this->slotUpdateTask(&eventCopy); setTaskCompleted(eventCopy.eventId); + //printf("#2 Slot thread slotIndex: %d eventCount: %d eventCopy.eventId: %d\n",slotIndex,eventCount,(int)eventCopy.eventId); } } - else { - safeMutex.ReleaseLock(); - } } } @@ -391,7 +331,6 @@ void ConnectionSlotThread::execute() { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); } catch(const exception &ex) { - //setRunningStatus(false); SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); @@ -408,51 +347,51 @@ void ConnectionSlotThread::execute() { ConnectionSlot::ConnectionSlot(ServerInterface* serverInterface, int playerIndex) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",__FILE__,__FUNCTION__,__LINE__); - this->mutexSocket = new Mutex(); - this->socket = NULL; - this->mutexCloseConnection = new Mutex(); - this->mutexPendingNetworkCommandList = new Mutex(); - this->socketSynchAccessor = new Mutex(); - this->connectedRemoteIPAddress = 0; - this->sessionKey = 0; - this->serverInterface = serverInterface; - this->playerIndex = playerIndex; - this->playerStatus = npst_None; - this->playerLanguage = ""; - this->playerUUID = ""; - this->platform = ""; - this->currentFrameCount = 0; - this->currentLagCount = 0; - this->gotLagCountWarning = false; - this->lastReceiveCommandListTime = 0; - this->receivedNetworkGameStatus = false; + this->mutexSocket = new Mutex(); + this->socket = NULL; + this->mutexCloseConnection = new Mutex(); + this->mutexPendingNetworkCommandList = new Mutex(); + this->socketSynchAccessor = new Mutex(); + this->connectedRemoteIPAddress = 0; + this->sessionKey = 0; + this->serverInterface = serverInterface; + this->playerIndex = playerIndex; + this->playerStatus = npst_None; + this->playerLanguage = ""; + this->playerUUID = ""; + this->platform = ""; + this->currentFrameCount = 0; + this->currentLagCount = 0; + this->gotLagCountWarning = false; + this->lastReceiveCommandListTime = 0; + this->receivedNetworkGameStatus = false; - this->skipLagCheck = false; - this->joinGameInProgress = false; - this->canAcceptConnections = true; - this->startInGameConnectionLaunch = false; - this->pauseForInGameConnection = false; - this->unPauseForInGameConnection = false; - this->sentSavedGameInfo = false; + this->skipLagCheck = false; + this->joinGameInProgress = false; + this->canAcceptConnections = true; + this->startInGameConnectionLaunch = false; + this->pauseForInGameConnection = false; + this->unPauseForInGameConnection = false; + this->sentSavedGameInfo = false; - this->setSocket(NULL); - this->slotThreadWorker = NULL; - static string mutexOwnerId = string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + intToStr(__LINE__); - this->slotThreadWorker = new ConnectionSlotThread(this->serverInterface,playerIndex); - this->slotThreadWorker->setUniqueID(mutexOwnerId); - this->slotThreadWorker->start(); + this->ready = false; + this->gotIntro = false; + this->connectedTime = 0; - this->ready = false; - this->gotIntro = false; - this->connectedTime = 0; - - networkGameDataSynchCheckOkMap = false; - networkGameDataSynchCheckOkTile = false; - networkGameDataSynchCheckOkTech = false; + this->networkGameDataSynchCheckOkMap = false; + this->networkGameDataSynchCheckOkTile = false; + this->networkGameDataSynchCheckOkTech = false; this->setNetworkGameDataSynchCheckTechMismatchReport(""); this->setReceivedDataSynchCheck(false); this->clearChatInfo(); + + this->setSocket(NULL); + this->slotThreadWorker = NULL; + static string mutexOwnerId = string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + intToStr(__LINE__); + this->slotThreadWorker = new ConnectionSlotThread(this->serverInterface,playerIndex); + this->slotThreadWorker->setUniqueID(mutexOwnerId); + this->slotThreadWorker->start(); } ConnectionSlot::~ConnectionSlot() { @@ -469,20 +408,26 @@ ConnectionSlot::~ConnectionSlot() { if(slotThreadWorker != NULL) { slotThreadWorker->signalQuit(); } - if(slotThreadWorker != NULL && slotThreadWorker->canShutdown(false) == true && + if( slotThreadWorker != NULL && + slotThreadWorker->canShutdown(false) == true && slotThreadWorker->getRunningStatus() == false) { //printf("#2 Ending client SLOT: %d\n",playerIndex); if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - delete slotThreadWorker; + + delete slotThreadWorker; + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); } - //else if(BaseThread::shutdownAndWait(slotThreadWorker) == true) { - else if(slotThreadWorker != NULL && slotThreadWorker->canShutdown(true) == true) { + else if(slotThreadWorker != NULL && + slotThreadWorker->canShutdown(true) == true) { + if(slotThreadWorker->getRunningStatus() == false) { //printf("#3 Ending client SLOT: %d\n",playerIndex); if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + delete slotThreadWorker; + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); } else { @@ -537,61 +482,28 @@ void ConnectionSlot::setReady() { } void ConnectionSlot::updateSlot(ConnectionSlotEvent *event) { - Chrono chrono; - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start(); - - //if(serverInterface->getGameHasBeenInitiated() == true && - //serverInterface->getAllowInGameConnections() == true) { - //printf("Checking updateSlot event = %p\n",event); - //} - if(event != NULL) { bool &socketTriggered = event->socketTriggered; bool checkForNewClients = (serverInterface->getGameHasBeenInitiated() == false || serverInterface->getAllowInGameConnections() == true); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis()); + //if((serverInterface->getGameHasBeenInitiated() == false || + // (serverInterface->getAllowInGameConnections() == true && this->isConnected() == false) || + // socketTriggered == true)) { + if(socketTriggered == true || + ((serverInterface->getGameHasBeenInitiated() == false || + serverInterface->getAllowInGameConnections() == true) && + this->isConnected() == false)) { - //if(chrono.getMillis() > 1) printf("In [%s::%s Line: %d] MUTEX LOCK held for msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,(long long int)chrono.getMillis()); - - //if(serverInterface->getGameHasBeenInitiated() == true && - //serverInterface->getAllowInGameConnections() == true) { - //printf("Checking for new client connection on slot, checkForNewClients: %d this->canAcceptConnections: %d\n",checkForNewClients,this->canAcceptConnections); - //} - - if((serverInterface->getGameHasBeenInitiated() == false || - (serverInterface->getAllowInGameConnections() == true && this->isConnected() == false) || - //(this->getSocket() != NULL && socketTriggered == true))) { - socketTriggered == true)) { - if(socketTriggered == true || - ((serverInterface->getGameHasBeenInitiated() == false || - serverInterface->getAllowInGameConnections() == true) && - this->isConnected() == false)) { - - //if(chrono.getMillis() > 1) printf("In [%s::%s Line: %d] MUTEX LOCK held for msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,(long long int)chrono.getMillis()); - - this->update(checkForNewClients,event->triggerId); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 4) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis()); - - //if(chrono.getMillis() > 1) printf("In [%s::%s Line: %d] MUTEX LOCK held for msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,(long long int)chrono.getMillis()); - - // This means no clients are trying to connect at the moment - //if(this->getSocket() == NULL) { - // checkForNewClients = false; - //} - } - //if(chrono.getMillis() > 1) printf("In [%s::%s Line: %d] MUTEX LOCK held for msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,(long long int)chrono.getMillis()); + this->update(checkForNewClients,event->triggerId); } + //} } if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",__FILE__,__FUNCTION__,__LINE__,chrono.getMillis()); } void ConnectionSlot::update(bool checkForNewClients,int lockedSlotIndex) { - //Chrono chrono; - //chrono.start(); try { clearThreadErrorList(); @@ -612,11 +524,11 @@ void ConnectionSlot::update(bool checkForNewClients,int lockedSlotIndex) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] BEFORE accept new client connection, serverInterface->getOpenSlotCount() = %d\n",__FILE__,__FUNCTION__,__LINE__,serverInterface->getOpenSlotCount()); //printf("Checking for new connections...\n"); - bool hasData = (serverInterface->getServerSocket() != NULL && serverInterface->getServerSocket()->hasDataToRead() == true); + bool hasData = (serverInterface->getServerSocket() != NULL && + serverInterface->getServerSocket()->hasDataToRead() == true); //printf("Server socket hasData: %d\n",hasData); if(hasData == true) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] about to accept new client connection playerIndex = %d\n",__FILE__,__FUNCTION__,__LINE__,playerIndex); Socket *newSocket = serverInterface->getServerSocket()->accept(false); @@ -736,19 +648,17 @@ void ConnectionSlot::update(bool checkForNewClients,int lockedSlotIndex) { // client REQUIRES a ping before completing intro // authentication - //if(gotIntro == true) { - NetworkMessagePing networkMessagePing; - if(receiveMessage(&networkMessagePing)) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - lastPingInfo = networkMessagePing; - } - else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugError).enabled) SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d]\nInvalid message type before intro handshake [%d]\nDisconnecting socket for slot: %d [%s].\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageType,this->playerIndex,this->getIpAddress().c_str()); - this->serverInterface->notifyBadClientConnectAttempt(this->getIpAddress()); - close(); - return; - } - //} + NetworkMessagePing networkMessagePing; + if(receiveMessage(&networkMessagePing)) { + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + lastPingInfo = networkMessagePing; + } + else { + if(SystemFlags::getSystemSettingType(SystemFlags::debugError).enabled) SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d]\nInvalid message type before intro handshake [%d]\nDisconnecting socket for slot: %d [%s].\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,networkMessageType,this->playerIndex,this->getIpAddress().c_str()); + this->serverInterface->notifyBadClientConnectAttempt(this->getIpAddress()); + close(); + return; + } } break; @@ -873,23 +783,18 @@ void ConnectionSlot::update(bool checkForNewClients,int lockedSlotIndex) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] got nmtCommandList gotIntro = %d\n",__FILE__,__FUNCTION__,__LINE__,gotIntro); - //throw megaglest_runtime_error("test"); - if(gotIntro == true) { NetworkMessageCommandList networkMessageCommandList; if(receiveMessage(&networkMessageCommandList)) { currentFrameCount = networkMessageCommandList.getFrameCount(); lastReceiveCommandListTime = time(NULL); - //printf("#1 Server slot got currentFrameCount = %d\n",currentFrameCount); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] currentFrameCount = %d\n",__FILE__,__FUNCTION__,__LINE__,currentFrameCount); MutexSafeWrapper safeMutexSlot(mutexPendingNetworkCommandList,CODE_AT_LINE); for(int i = 0; i < networkMessageCommandList.getCommandCount(); ++i) { vctPendingNetworkCommandList.push_back(*networkMessageCommandList.getCommand(i)); } - safeMutexSlot.ReleaseLock(); //printf("Got commands from client frame: %d count: %d\n",currentFrameCount,vctPendingNetworkCommandList.size()); //printf("#2 Server slot got currentFrameCount = %d\n",currentFrameCount); @@ -926,8 +831,6 @@ void ConnectionSlot::update(bool checkForNewClients,int lockedSlotIndex) { this->platform = networkMessageIntro.getPlayerPlatform(); //printf("Got uuid from client [%s]\n",this->playerUUID.c_str()); - - //printf("\n\n\n ##### GOT this->playerLanguage [%s]\n\n\n",this->playerLanguage.c_str()); if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] got name [%s] versionString [%s], msgSessionId = %d\n",__FILE__,__FUNCTION__,name.c_str(),versionString.c_str(),msgSessionId); if(msgSessionId != sessionKey) { @@ -1004,7 +907,6 @@ void ConnectionSlot::update(bool checkForNewClients,int lockedSlotIndex) { if(serverInterface->getGameHasBeenInitiated() == true && serverInterface->getAllowInGameConnections() == true) { - //int factionIndex = this->serverInterface->gameSettings.getFactionIndexForStartLocation(playerIndex); this->serverInterface->gameSettings.setNetworkPlayerStatuses(factionIndex,npst_None); } @@ -1066,7 +968,6 @@ void ConnectionSlot::update(bool checkForNewClients,int lockedSlotIndex) { if(receiveMessage(&networkMessageLaunch)) { if(networkMessageLaunch.getMessageType() == nmtLaunch) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Lined: %d] got nmtLaunch\n",__FILE__,__FUNCTION__,__LINE__); - //printf("Got launch request from client joinGameInProgress = %d joinGameInProgress = %d!\n",joinGameInProgress,joinGameInProgress); } else if(networkMessageLaunch.getMessageType() == nmtBroadCastSetup) { @@ -1081,16 +982,18 @@ void ConnectionSlot::update(bool checkForNewClients,int lockedSlotIndex) { } int minHeadLessPlayersRequired = Config::getInstance().getInt("MinHeadlessPlayersRequired","2"); - if(this->joinGameInProgress == false && networkMessageLaunch.getMessageType() == nmtLaunch && - this->ready == false && - this->serverInterface->getConnectedSlotCount(true) < minHeadLessPlayersRequired) { + if(this->joinGameInProgress == false && + networkMessageLaunch.getMessageType() == nmtLaunch && + this->ready == false && + this->serverInterface->getConnectedSlotCount(true) < minHeadLessPlayersRequired) { + Lang &lang= Lang::getInstance(); const vector languageList = this->serverInterface->getGameSettings()->getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { + for(unsigned int index = 0; index < languageList.size(); ++index) { char szBuf[4096]=""; string msgTemplate = "You must have have at least %d player(s) connected to start this game!"; - if(lang.hasString("HeadlessAdminRequiresMorePlayers",languageList[i]) == true) { - msgTemplate = lang.getString("HeadlessAdminRequiresMorePlayers",languageList[i]); + if(lang.hasString("HeadlessAdminRequiresMorePlayers",languageList[index]) == true) { + msgTemplate = lang.getString("HeadlessAdminRequiresMorePlayers",languageList[index]); } #ifdef WIN32 _snprintf(szBuf,4095,msgTemplate.c_str(),minHeadLessPlayersRequired); @@ -1100,10 +1003,8 @@ void ConnectionSlot::update(bool checkForNewClients,int lockedSlotIndex) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] %s\n",__FILE__,__FUNCTION__,__LINE__,szBuf); string sMsg = szBuf; - bool echoLocal = lang.isLanguageLocal(languageList[i]); - this->serverInterface->sendTextMessage(sMsg,-1, echoLocal, languageList[i], this->getPlayerIndex()); - - //printf("Lang [%s] msgTemplate [%s] echoLocal = %d\n",languageList[i].c_str(),msgTemplate.c_str(),echoLocal); + bool echoLocal = lang.isLanguageLocal(languageList[index]); + this->serverInterface->sendTextMessage(sMsg,-1, echoLocal, languageList[index], this->getPlayerIndex()); } } else { @@ -1114,19 +1015,18 @@ void ConnectionSlot::update(bool checkForNewClients,int lockedSlotIndex) { //printf("Connection slot got networkMessageLaunch.getMessageType() = %d, got map [%s]\n",networkMessageLaunch.getMessageType(),gameSettings.getMap().c_str()); //printf("\n\n\n\n=====Connection slot got settings:\n%s\n",gameSettings.toString().c_str()); - //this->serverInterface->setGameSettings(&gameSettingsBuffer,false); this->serverInterface->broadcastGameSetup(&gameSettingsBuffer, true); } - if(this->joinGameInProgress == false && networkMessageLaunch.getMessageType() == nmtLaunch) { + if(this->joinGameInProgress == false && + networkMessageLaunch.getMessageType() == nmtLaunch) { + this->serverInterface->setMasterserverAdminRequestLaunch(true); } - else if(this->joinGameInProgress == true && networkMessageLaunch.getMessageType() == nmtLaunch) { + else if(this->joinGameInProgress == true && + networkMessageLaunch.getMessageType() == nmtLaunch) { //printf("!!! setStartInGameConnectionLaunch for client joinGameInProgress = %d!\n",joinGameInProgress); - //GameSettings gameSettingsBuffer; - //networkMessageLaunch.buildGameSettings(&gameSettingsBuffer); - int factionIndex = this->serverInterface->gameSettings.getFactionIndexForStartLocation(playerIndex); this->serverInterface->gameSettings.setFactionControl(factionIndex,ctNetwork); this->serverInterface->gameSettings.setNetworkPlayerName(factionIndex,this->name); @@ -1248,11 +1148,8 @@ void ConnectionSlot::update(bool checkForNewClients,int lockedSlotIndex) { vctFileList.push_back(std::pair(Config::getMapPath(serverInterface->getGameSettings()->getMap(),scenarioDir,false),mapCRC)); } - //for(int i = 0; i < vctFileList.size(); i++) - //{ NetworkMessageSynchNetworkGameDataFileCRCCheck networkMessageSynchNetworkGameDataFileCRCCheck((int)vctFileList.size(), 1, vctFileList[0].second, vctFileList[0].first); sendMessage(&networkMessageSynchNetworkGameDataFileCRCCheck); - //} } else { if(networkGameDataSynchCheckOkTech == false) { @@ -1349,7 +1246,6 @@ void ConnectionSlot::update(bool checkForNewClients,int lockedSlotIndex) { case nmtSwitchSetupRequest: { //printf("Got nmtSwitchSetupRequest A gotIntro = %d\n",gotIntro); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] got nmtSwitchSetupRequest gotIntro = %d\n",__FILE__,__FUNCTION__,__LINE__,gotIntro); if(gotIntro == true) { @@ -1361,7 +1257,6 @@ void ConnectionSlot::update(bool checkForNewClients,int lockedSlotIndex) { int slotIdx = switchSetupRequest.getCurrentSlotIndex(); //int newSlotIdx = switchSetupRequest.getToSlotIndex(); - //printf("slotIdx = %d newSlotIdx = %d\n",slotIdx,newSlotIdx); if(serverInterface->getSwitchSetupRequests(slotIdx) == NULL) { @@ -1379,7 +1274,6 @@ void ConnectionSlot::update(bool checkForNewClients,int lockedSlotIndex) { //printf("In [%s::%s Line %d] networkPlayerName [%s]\n",__FILE__,__FUNCTION__,__LINE__,serverInterface->getSwitchSetupRequests()[factionIdx]->getNetworkPlayerName().c_str()); if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line %d] networkPlayerName [%s]\n",__FILE__,__FUNCTION__,__LINE__,serverInterface->getSwitchSetupRequests()[slotIdx]->getNetworkPlayerName().c_str()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] factionIdx = %d, switchSetupRequest.getNetworkPlayerName() [%s] switchSetupRequest.getNetworkPlayerStatus() = %d, switchSetupRequest.getSwitchFlags() = %d\n",__FILE__,__FUNCTION__,__LINE__,slotIdx,switchSetupRequest.getNetworkPlayerName().c_str(),switchSetupRequest.getNetworkPlayerStatus(),switchSetupRequest.getSwitchFlags()); } else { @@ -1540,18 +1434,18 @@ void ConnectionSlot::validateConnection() { } void ConnectionSlot::resetJoinGameInProgressFlags() { - this->gotIntro = false; - this->skipLagCheck = false; - this->joinGameInProgress = false; - this->ready= false; + this->gotIntro = false; + this->skipLagCheck = false; + this->joinGameInProgress = false; + this->ready = false; } void ConnectionSlot::setJoinGameInProgressFlags() { - this->gotIntro = true; - this->skipLagCheck = true; - this->joinGameInProgress = true; - this->ready= false; - this->sentSavedGameInfo = false; + this->gotIntro = true; + this->skipLagCheck = true; + this->joinGameInProgress = true; + this->ready = false; + this->sentSavedGameInfo = false; } void ConnectionSlot::close() { @@ -1561,17 +1455,16 @@ void ConnectionSlot::close() { //if(serverInterface->getAllowInGameConnections() == true) { //printf("Closing connection slot!\n"); //} - //printf("ConnectionSlot::close() #1 this->getSocket() = %p\n",this->getSocket()); - this->gotIntro = false; - this->skipLagCheck = false; - this->joinGameInProgress = false; - this->sentSavedGameInfo = false; - this->pauseForInGameConnection = false; - this->unPauseForInGameConnection = false; - this->ready= false; - this->connectedTime = 0; + this->gotIntro = false; + this->skipLagCheck = false; + this->joinGameInProgress = false; + this->sentSavedGameInfo = false; + this->pauseForInGameConnection = false; + this->unPauseForInGameConnection = false; + this->ready = false; + this->connectedTime = 0; if(this->slotThreadWorker != NULL) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); @@ -1584,7 +1477,6 @@ void ConnectionSlot::close() { //printf("ConnectionSlot::close() #2 this->getSocket() = %p\n",this->getSocket()); MutexSafeWrapper safeMutex(mutexCloseConnection,CODE_AT_LINE); - bool updateServerListener = (this->getSocket() != NULL); //printf("ConnectionSlot::close() #3 this->getSocket() = %p updateServerListener = %d\n",this->getSocket(),updateServerListener); @@ -1593,7 +1485,6 @@ void ConnectionSlot::close() { safeMutex.ReleaseLock(); if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s LINE: %d]\n",__FILE__,__FUNCTION__,__LINE__); - //printf("Closing slot for playerIndex = %d updateServerListener = %d ready = %d\n",playerIndex,updateServerListener,ready); if(updateServerListener == true) { @@ -1601,10 +1492,6 @@ void ConnectionSlot::close() { serverInterface->updateListen(); } - //ready = false; - //gotIntro = false; - - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] END\n",__FILE__,__FUNCTION__); } @@ -1613,7 +1500,6 @@ Mutex * ConnectionSlot::getServerSynchAccessor() { } void ConnectionSlot::signalUpdate(ConnectionSlotEvent *event) { - //assert(slotThreadWorker != NULL); if(slotThreadWorker != NULL) { slotThreadWorker->signalUpdate(event); } @@ -1635,7 +1521,6 @@ void ConnectionSlot::sendMessage(NetworkMessage* networkMessage) { NetworkMessageText *textMsg = dynamic_cast(networkMessage); if(textMsg != NULL) { //printf("\n\n\n~~~ SERVER HAS NetworkMessageText target [%s] player [%s] msg[%s]\n\n\n",textMsg->getTargetLanguage().c_str(),this->getNetworkPlayerLanguage().c_str(), textMsg->getText().c_str()); - if(textMsg->getTargetLanguage() != "" && textMsg->getTargetLanguage() != this->getNetworkPlayerLanguage()) { return; @@ -1658,7 +1543,6 @@ vector ConnectionSlot::getPendingNetworkCommandList(bool clearLi vctPendingNetworkCommandList.clear(); } } - safeMutexSlot.ReleaseLock(); return ret; } @@ -1668,12 +1552,9 @@ void ConnectionSlot::clearPendingNetworkCommandList() { if(vctPendingNetworkCommandList.empty() == false) { vctPendingNetworkCommandList.clear(); } - safeMutexSlot.ReleaseLock(); } bool ConnectionSlot::hasValidSocketId() { - //bool result = (this->getSocket() != NULL && this->getSocket()->getSocketId() > 0); - //return result; bool result = false; MutexSafeWrapper safeMutexSlot(mutexSocket,CODE_AT_LINE); if(socket != NULL && socket->getSocketId() > 0) { @@ -1733,18 +1614,11 @@ void ConnectionSlot::deleteSocket() { bool ConnectionSlot::hasDataToRead() { bool result = false; - //printf("==> #1 Slot hasDataToRead()\n"); - MutexSafeWrapper safeMutexSlot(mutexSocket,CODE_AT_LINE); - - //printf("==> #2 Slot hasDataToRead()\n"); - if(socket != NULL && socket->hasDataToRead() == true) { result = true; } - //printf("==> #3 Slot hasDataToRead()\n"); - return result; } diff --git a/source/glest_game/network/server_interface.cpp b/source/glest_game/network/server_interface.cpp index 9f6ba1278..cc6cc00fa 100644 --- a/source/glest_game/network/server_interface.cpp +++ b/source/glest_game/network/server_interface.cpp @@ -53,19 +53,19 @@ const int MASTERSERVER_HEARTBEAT_GAME_STATUS_SECONDS = 30; ServerInterface::ServerInterface(bool publishEnabled) :GameNetworkInterface() { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - allowInGameConnections = false; - gameLaunched = false; + allowInGameConnections = false; + gameLaunched = false; - serverSynchAccessor = new Mutex(); - switchSetupRequestsSynchAccessor = new Mutex(); + serverSynchAccessor = new Mutex(); + switchSetupRequestsSynchAccessor = new Mutex(); - for(int i= 0; i < GameConstants::maxPlayers; ++i) { - slotAccessorMutexes[i] = new Mutex(); + for(int index = 0; index < GameConstants::maxPlayers; ++index) { + slotAccessorMutexes[index] = new Mutex(); } - masterServerThreadAccessor = new Mutex(); - textMessageQueueThreadAccessor = new Mutex(); + masterServerThreadAccessor = new Mutex(); + textMessageQueueThreadAccessor = new Mutex(); broadcastMessageQueueThreadAccessor = new Mutex(); - inBroadcastMessageThreadAccessor = new Mutex(); + inBroadcastMessageThreadAccessor = new Mutex(); serverSocketAdmin = NULL; nextEventId = 1; @@ -88,7 +88,7 @@ ServerInterface::ServerInterface(bool publishEnabled) :GameNetworkInterface() { // give current connection status info #ifndef __APPLE__ try { - serverSocketAdmin = new ServerSocket(true); + serverSocketAdmin = new ServerSocket(true); serverSocketAdmin->setBlock(false); serverSocketAdmin->setBindPort(Config::getInstance().getInt("ServerAdminPort", intToStr(GameConstants::serverAdminPort).c_str())); serverSocketAdmin->setBindSpecificAddress(Config::getInstance().getString("ServerAdminBindAddress", "127.0.0.1")); @@ -98,6 +98,7 @@ ServerInterface::ServerInterface(bool publishEnabled) :GameNetworkInterface() { char szBuf[8096]=""; snprintf(szBuf,8096,"In [%s::%s Line: %d] Warning Server admin port bind/listen error:\n%s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); SystemFlags::OutputDebug(SystemFlags::debugError,szBuf); + if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"%s",szBuf); } #endif @@ -110,23 +111,23 @@ ServerInterface::ServerInterface(bool publishEnabled) :GameNetworkInterface() { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] maxFrameCountLagAllowed = %f, maxFrameCountLagAllowedEver = %f, maxClientLagTimeAllowed = %f, maxClientLagTimeAllowedEver = %f\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,maxFrameCountLagAllowed,maxFrameCountLagAllowedEver,maxClientLagTimeAllowed,maxClientLagTimeAllowedEver); - for(int i= 0; i < GameConstants::maxPlayers; ++i) { - slots[i] = NULL; - switchSetupRequests[i] = NULL; + for(int index = 0; index < GameConstants::maxPlayers; ++index) { + slots[index] = NULL; + switchSetupRequests[index] = NULL; } if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + serverSocket.setBlock(false); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); serverSocket.setBindPort(Config::getInstance().getInt("PortServer", intToStr(GameConstants::serverPort).c_str())); + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - gameStatsThreadAccessor = new Mutex(); - gameStats = NULL; + gameStatsThreadAccessor = new Mutex(); + gameStats = NULL; - Config &config = Config::getInstance(); - vector results; - string scenarioDir = ""; + Config &config = Config::getInstance(); + string scenarioDir = ""; vector pathList = config.getPathListForType(ptMaps,scenarioDir); vector invalidMapList; vector allMaps = MapPreview::findAllValidMaps(pathList,scenarioDir,false,true,&invalidMapList); @@ -135,7 +136,7 @@ ServerInterface::ServerInterface(bool publishEnabled) :GameNetworkInterface() { printf("No maps were found (srv)!\n"); } std::sort(allMaps.begin(),allMaps.end()); - results.clear(); + vector results; copy(allMaps.begin(), allMaps.end(), std::back_inserter(results)); mapFiles = results; @@ -145,7 +146,7 @@ ServerInterface::ServerInterface(bool publishEnabled) :GameNetworkInterface() { //throw megaglest_runtime_error("No tile-sets were found!"); printf("No tile-sets were found (srv)!"); } - tilesetFiles= results; + tilesetFiles = results; results.clear(); findDirs(config.getPathListForType(ptTechs), results); @@ -153,7 +154,7 @@ ServerInterface::ServerInterface(bool publishEnabled) :GameNetworkInterface() { //throw megaglest_runtime_error("No tech-trees were found!"); printf("No tech-trees were found (srv)!\n"); } - techTreeFiles= results; + techTreeFiles = results; if(Config::getInstance().getBool("EnableFTPServer","true") == true) { std::pair mapsPath; @@ -251,21 +252,20 @@ void ServerInterface::shutdownMasterserverPublishThread() { ServerInterface::~ServerInterface() { //printf("===> Destructor for ServerInterface\n"); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); masterController.clearSlaves(true); exitServer = true; - for(int i= 0; i < GameConstants::maxPlayers; ++i) { - if(slots[i] != NULL) { - MutexSafeWrapper safeMutex(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - delete slots[i]; - slots[i]=NULL; + for(int index = 0; index < GameConstants::maxPlayers; ++index) { + if(slots[index] != NULL) { + MutexSafeWrapper safeMutex(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); + delete slots[index]; + slots[index] = NULL; } - if(switchSetupRequests[i] != NULL) { - delete switchSetupRequests[i]; - switchSetupRequests[i]=NULL; + if(switchSetupRequests[index] != NULL) { + delete switchSetupRequests[index]; + switchSetupRequests[index] = NULL; } } @@ -279,9 +279,9 @@ ServerInterface::~ServerInterface() { simpleTask(NULL,NULL); } - for(int i= 0; i < GameConstants::maxPlayers; ++i) { - delete slotAccessorMutexes[i]; - slotAccessorMutexes[i] = NULL; + for(int index = 0; index < GameConstants::maxPlayers; ++index) { + delete slotAccessorMutexes[index]; + slotAccessorMutexes[index] = NULL; } delete textMessageQueueThreadAccessor; @@ -302,8 +302,8 @@ ServerInterface::~ServerInterface() { delete serverSocketAdmin; serverSocketAdmin = NULL; - for(int i = 0; i < (int)broadcastMessageQueue.size(); ++i) { - pair &item = broadcastMessageQueue[i]; + for(int index = 0; index < (int)broadcastMessageQueue.size(); ++index) { + pair &item = broadcastMessageQueue[index]; if(item.first != NULL) { delete item.first; } @@ -340,11 +340,10 @@ void ServerInterface::setSwitchSetupRequests(int index,SwitchSetupRequest *ptr) int ServerInterface::isValidClientType(uint32 clientIp) { int result = 0; - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - if(slots[i] != NULL) { - MutexSafeWrapper safeMutex(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - - Socket *socket = slots[i]->getSocket(); + for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { + MutexSafeWrapper safeMutex(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); + if(slots[index] != NULL) { + Socket *socket = slots[index]->getSocket(); if(socket != NULL) { uint32 slotIp = socket->getConnectedIPAddress(socket->getIpAddress()); if(slotIp == clientIp) { @@ -360,7 +359,10 @@ int ServerInterface::isValidClientType(uint32 clientIp) { int ServerInterface::isClientAllowedToGetFile(uint32 clientIp, const char *username, const char *filename) { int result = 1; - if(username != NULL && strlen(username) > 0 && filename != NULL && strlen(filename) > 0) { + if( username != NULL && + strlen(username) > 0 && + filename != NULL && + strlen(filename) > 0) { string user = username; string file = filename; @@ -371,17 +373,16 @@ int ServerInterface::isClientAllowedToGetFile(uint32 clientIp, const char *usern result = 0; } else { - char szIP[100]=""; + char szIP[100] = ""; Ip::Inet_NtoA(clientIp,szIP); string clientIP = szIP; - //string serverIP = serverSocket.getIp(); std::vector serverList = Socket::getLocalIPAddressList(); result = 0; - for(unsigned int i = 0; i < serverList.size(); ++i) { - string serverIP = serverList[i]; + for(unsigned int index = 0; index < serverList.size(); ++index) { + string serverIP = serverList[index]; - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d clientIP [%s] serverIP [%s] %d / %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,clientIP.c_str(),serverIP.c_str(),i,serverList.size()); + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d clientIP [%s] serverIP [%s] %d / %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,clientIP.c_str(),serverIP.c_str(),index,serverList.size()); vector clientTokens; Tokenize(clientIP,clientTokens,"."); @@ -413,9 +414,8 @@ void ServerInterface::addClientToServerIPAddress(uint32 clientIp, uint32 ServerI void ServerInterface::addSlot(int playerIndex) { //printf("Adding slot for playerIndex = %d, serverSocket.isPortBound() = %d\n",playerIndex,serverSocket.isPortBound()); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - //assert(playerIndex >= 0 && playerIndex < GameConstants::maxPlayers); + if(playerIndex < 0 || playerIndex >= GameConstants::maxPlayers) { char szBuf[8096]=""; snprintf(szBuf,8096,"In [%s::%s %d] playerIndex is invalid = %d",extractFileFromDirectoryPath(extractFileFromDirectoryPath(__FILE__).c_str()).c_str(),__FUNCTION__,__LINE__,playerIndex); @@ -431,49 +431,66 @@ void ServerInterface::addSlot(int playerIndex) { } if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[playerIndex],CODE_AT_LINE_X(playerIndex)); + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + ConnectionSlot *slot = slots[playerIndex]; if(slot != NULL) { - slots[playerIndex]=NULL; + slots[playerIndex] = NULL; } slots[playerIndex] = new ConnectionSlot(this, playerIndex); + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + safeMutexSlot.ReleaseLock(); delete slot; + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + safeMutex.ReleaseLock(); + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + updateListen(); + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); } void ServerInterface::removeSlot(int playerIndex, int lockedSlotIndex) { //printf("Removing slot for playerIndex = %d, serverSocket.isPortBound() = %d\n",playerIndex,serverSocket.isPortBound()); - //printf("Removing connection slot!\n"); + + if(playerIndex < 0 || playerIndex >= GameConstants::maxPlayers) { + char szBuf[8096]=""; + snprintf(szBuf,8096,"In [%s::%s %d] playerIndex is invalid = %d",extractFileFromDirectoryPath(extractFileFromDirectoryPath(__FILE__).c_str()).c_str(),__FUNCTION__,__LINE__,playerIndex); + throw megaglest_runtime_error(szBuf); + } Lang &lang= Lang::getInstance(); if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] playerIndex = %d, lockedSlotIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,playerIndex,lockedSlotIndex); + MutexSafeWrapper safeMutex(serverSynchAccessor,CODE_AT_LINE); MutexSafeWrapper safeMutexSlot(NULL,CODE_AT_LINE_X(playerIndex)); if(playerIndex != lockedSlotIndex) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] playerIndex = %d, lockedSlotIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,playerIndex,lockedSlotIndex); safeMutexSlot.setMutex(slotAccessorMutexes[playerIndex],CODE_AT_LINE_X(playerIndex)); } - ConnectionSlot *slot = slots[playerIndex]; - bool notifyDisconnect = false; + vector msgList; - const vector languageList = this->gameSettings.getUniqueNetworkPlayerLanguages(); + ConnectionSlot *slot = slots[playerIndex]; + bool notifyDisconnect = false; + const vector languageList = this->gameSettings.getUniqueNetworkPlayerLanguages(); if(slot != NULL) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] playerIndex = %d, lockedSlotIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,playerIndex,lockedSlotIndex); if(slot->getLastReceiveCommandListTime() > 0) { char szBuf[4096] = ""; - for(unsigned int i = 0; i < languageList.size(); ++i) { + for(unsigned int index = 0; index < languageList.size(); ++index) { string msgTemplate = "Player %s, disconnected from the game."; - if(lang.hasString("PlayerDisconnected",languageList[i]) == true) { - msgTemplate = lang.getString("PlayerDisconnected",languageList[i]); + if(lang.hasString("PlayerDisconnected",languageList[index]) == true) { + msgTemplate = lang.getString("PlayerDisconnected",languageList[index]); } #ifdef WIN32 _snprintf(szBuf,4095,msgTemplate.c_str(),slot->getName().c_str()); @@ -489,21 +506,28 @@ void ServerInterface::removeSlot(int playerIndex, int lockedSlotIndex) { } } if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] playerIndex = %d, lockedSlotIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,playerIndex,lockedSlotIndex); + slots[playerIndex]= NULL; safeMutexSlot.ReleaseLock(); safeMutex.ReleaseLock(); + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] playerIndex = %d, lockedSlotIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,playerIndex,lockedSlotIndex); + if(slot != NULL) slot->close(); delete slot; + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] playerIndex = %d, lockedSlotIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,playerIndex,lockedSlotIndex); + updateListen(); if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] playerIndex = %d, lockedSlotIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,playerIndex,lockedSlotIndex); + if(notifyDisconnect == true) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] playerIndex = %d, lockedSlotIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,playerIndex,lockedSlotIndex); - for(unsigned int j = 0; j < languageList.size(); ++j) { - bool localEcho = lang.isLanguageLocal(languageList[j]); - queueTextMessage(msgList[j],-1, localEcho, languageList[j]); + + for(unsigned int index = 0; index < languageList.size(); ++index) { + bool localEcho = lang.isLanguageLocal(languageList[index]); + queueTextMessage(msgList[index],-1, localEcho, languageList[index]); } } if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] playerIndex = %d, lockedSlotIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,playerIndex,lockedSlotIndex); @@ -515,14 +539,12 @@ bool ServerInterface::switchSlot(int fromPlayerIndex, int toPlayerIndex) { //printf("#1 Server is switching slots\n"); - //assert(fromPlayerIndex >= 0 && fromPlayerIndex < GameConstants::maxPlayers); if(fromPlayerIndex < 0 || fromPlayerIndex >= GameConstants::maxPlayers) { char szBuf[8096]=""; snprintf(szBuf,8096,"In [%s::%s %d] fromPlayerIndex is invalid = %d",extractFileFromDirectoryPath(extractFileFromDirectoryPath(__FILE__).c_str()).c_str(),__FUNCTION__,__LINE__,fromPlayerIndex); throw megaglest_runtime_error(szBuf); } - //assert(toPlayerIndex >= 0 && toPlayerIndex < GameConstants::maxPlayers); if(toPlayerIndex < 0 || toPlayerIndex >= GameConstants::maxPlayers) { char szBuf[8096]=""; snprintf(szBuf,8096,"In [%s::%s %d] toPlayerIndex is invalid = %d",extractFileFromDirectoryPath(extractFileFromDirectoryPath(__FILE__).c_str()).c_str(),__FUNCTION__,__LINE__,toPlayerIndex); @@ -546,9 +568,9 @@ bool ServerInterface::switchSlot(int fromPlayerIndex, int toPlayerIndex) { slots[fromPlayerIndex]->setPlayerIndex(toPlayerIndex); slots[toPlayerIndex]->setPlayerIndex(fromPlayerIndex); - ConnectionSlot *tmp = slots[toPlayerIndex]; - slots[toPlayerIndex] = slots[fromPlayerIndex]; - slots[fromPlayerIndex] = tmp; + ConnectionSlot *tmp = slots[toPlayerIndex]; + slots[toPlayerIndex] = slots[fromPlayerIndex]; + slots[fromPlayerIndex] = tmp; safeMutex.ReleaseLock(); @@ -577,15 +599,27 @@ bool ServerInterface::switchSlot(int fromPlayerIndex, int toPlayerIndex) { } ConnectionSlot *ServerInterface::getSlot(int playerIndex) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[playerIndex],CODE_AT_LINE_X(i)); + if(playerIndex < 0 || playerIndex >= GameConstants::maxPlayers) { + char szBuf[8096]=""; + snprintf(szBuf,8096,"In [%s::%s %d] playerIndex is invalid = %d",extractFileFromDirectoryPath(extractFileFromDirectoryPath(__FILE__).c_str()).c_str(),__FUNCTION__,__LINE__,playerIndex); + throw megaglest_runtime_error(szBuf); + } + + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[playerIndex],CODE_AT_LINE_X(playerIndex)); ConnectionSlot *result = slots[playerIndex]; return result; } -bool ServerInterface::isClientConnected(int index) { +bool ServerInterface::isClientConnected(int playerIndex) { + if(playerIndex < 0 || playerIndex >= GameConstants::maxPlayers) { + char szBuf[8096]=""; + snprintf(szBuf,8096,"In [%s::%s %d] playerIndex is invalid = %d",extractFileFromDirectoryPath(extractFileFromDirectoryPath(__FILE__).c_str()).c_str(),__FUNCTION__,__LINE__,playerIndex); + throw megaglest_runtime_error(szBuf); + } + bool result = false; - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(i)); - if(slots[index] != NULL && slots[index]->isConnected() == true) { + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[playerIndex],CODE_AT_LINE_X(playerIndex)); + if(slots[playerIndex] != NULL && slots[playerIndex]->isConnected() == true) { result = true; } return result; @@ -593,8 +627,8 @@ bool ServerInterface::isClientConnected(int index) { bool ServerInterface::hasClientConnection() { bool result = false; - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - if(isClientConnected(i) == true) { + for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { + if(isClientConnected(index) == true) { result = true; break; } @@ -604,9 +638,9 @@ bool ServerInterface::hasClientConnection() { int ServerInterface::getSlotCount() { int slotCount = 0; - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - if(slots[i] != NULL) { + for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); + if(slots[index] != NULL) { ++slotCount; } } @@ -615,11 +649,11 @@ int ServerInterface::getSlotCount() { int ServerInterface::getConnectedSlotCount(bool authenticated) { int connectedSlotCount = 0; - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - if(slots[i] != NULL && slots[i]->isConnected() == true) { + for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); + if(slots[index] != NULL && slots[index]->isConnected() == true) { if(authenticated == false || - (authenticated == true && slots[i]->getConnectHasHandshaked() == true)) { + (authenticated == true && slots[index]->getConnectHasHandshaked() == true)) { ++connectedSlotCount; } } @@ -636,9 +670,6 @@ int64 ServerInterface::getNextEventId() { } std::pair ServerInterface::clientLagCheck(ConnectionSlot *connectionSlot, bool skipNetworkBroadCast) { - Chrono chrono; - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start(); - std::pair clientLagExceededOrWarned = std::make_pair(false, false); static bool alreadyInLagCheck = false; @@ -657,13 +688,12 @@ std::pair ServerInterface::clientLagCheck(ConnectionSlot *connectionS (resumeGameStartTime > 0 && difftime((long int)time(NULL),resumeGameStartTime) >= LAG_CHECK_GRACE_PERIOD))) { if(connectionSlot != NULL && connectionSlot->isConnected() == true) { - double clientLag = this->getCurrentFrameCount() - connectionSlot->getCurrentFrameCount(); - double clientLagCount = (gameSettings.getNetworkFramePeriod() > 0 ? (clientLag / gameSettings.getNetworkFramePeriod()) : 0); + + double clientLag = this->getCurrentFrameCount() - connectionSlot->getCurrentFrameCount(); + double clientLagCount = (gameSettings.getNetworkFramePeriod() > 0 ? (clientLag / gameSettings.getNetworkFramePeriod()) : 0); connectionSlot->setCurrentLagCount(clientLagCount); - double clientLagTime = difftime((long int)time(NULL),connectionSlot->getLastReceiveCommandListTime()); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); + double clientLagTime = difftime((long int)time(NULL),connectionSlot->getLastReceiveCommandListTime()); if(this->getCurrentFrameCount() > 0) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] playerIndex = %d, clientLag = %f, clientLagCount = %f, this->getCurrentFrameCount() = %d, connectionSlot->getCurrentFrameCount() = %d, clientLagTime = %f\n", @@ -698,19 +728,19 @@ std::pair ServerInterface::clientLagCheck(ConnectionSlot *connectionS Lang &lang= Lang::getInstance(); const vector languageList = this->gameSettings.getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { + for(unsigned int index = 0; index < languageList.size(); ++index) { char szBuf[4096]=""; string msgTemplate = "DROPPING %s, exceeded max allowed LAG count of %f [time = %f], clientLag = %f [%f], disconnecting client."; if(lang.hasString("ClientLagDropping") == true) { - msgTemplate = lang.getString("ClientLagDropping",languageList[i]); + msgTemplate = lang.getString("ClientLagDropping",languageList[index]); } if(gameSettings.getNetworkPauseGameForLaggedClients() == true && ((maxFrameCountLagAllowedEver <= 0 || clientLagCount <= maxFrameCountLagAllowedEver) && (maxClientLagTimeAllowedEver <= 0 || clientLagTime <= maxClientLagTimeAllowedEver))) { msgTemplate = "PAUSING GAME TEMPORARILY for %s, exceeded max allowed LAG count of %f [time = %f], clientLag = %f [%f], waiting for client to catch up..."; if(lang.hasString("ClientLagPausing") == true) { - msgTemplate = lang.getString("ClientLagPausing",languageList[i]); + msgTemplate = lang.getString("ClientLagPausing",languageList[index]); } } #ifdef WIN32 @@ -720,12 +750,10 @@ std::pair ServerInterface::clientLagCheck(ConnectionSlot *connectionS #endif if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] %s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - if(skipNetworkBroadCast == false) { string sMsg = szBuf; - bool echoLocal = lang.isLanguageLocal(languageList[i]); - sendTextMessage(sMsg,-1, echoLocal, languageList[i], connectionSlot->getPlayerIndex()); + bool echoLocal = lang.isLanguageLocal(languageList[index]); + sendTextMessage(sMsg,-1, echoLocal, languageList[index], connectionSlot->getPlayerIndex()); } } @@ -737,7 +765,6 @@ std::pair ServerInterface::clientLagCheck(ConnectionSlot *connectionS connectionSlot->close(); } - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); } // New lag check warning else if((maxFrameCountLagAllowed > 0 && warnFrameCountLagPercent > 0 && @@ -751,12 +778,12 @@ std::pair ServerInterface::clientLagCheck(ConnectionSlot *connectionS Lang &lang= Lang::getInstance(); const vector languageList = this->gameSettings.getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { + for(unsigned int index = 0; index < languageList.size(); ++index) { char szBuf[4096]=""; string msgTemplate = "LAG WARNING for %s, may exceed max allowed LAG count of %f [time = %f], clientLag = %f [%f], WARNING..."; if(lang.hasString("ClientLagWarning") == true) { - msgTemplate = lang.getString("ClientLagWarning",languageList[i]); + msgTemplate = lang.getString("ClientLagWarning",languageList[index]); } #ifdef WIN32 @@ -766,20 +793,16 @@ std::pair ServerInterface::clientLagCheck(ConnectionSlot *connectionS #endif if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] %s\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,szBuf); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - if(skipNetworkBroadCast == false) { string sMsg = szBuf; - bool echoLocal = lang.isLanguageLocal(languageList[i]); - sendTextMessage(sMsg,-1, echoLocal, languageList[i], connectionSlot->getPlayerIndex()); + bool echoLocal = lang.isLanguageLocal(languageList[index]); + sendTextMessage(sMsg,-1, echoLocal, languageList[index], connectionSlot->getPlayerIndex()); } } } } else if(connectionSlot->getLagCountWarning() == true) { connectionSlot->setLagCountWarning(false); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); } } } @@ -792,33 +815,27 @@ std::pair ServerInterface::clientLagCheck(ConnectionSlot *connectionS throw megaglest_runtime_error(ex.what()); } - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - alreadyInLagCheck = false; return clientLagExceededOrWarned; } void ServerInterface::updateSocketTriggeredList(std::map & socketTriggeredList) { - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - ConnectionSlot* connectionSlot= slots[i]; + for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); + ConnectionSlot *connectionSlot = slots[index]; if(connectionSlot != NULL) { PLATFORM_SOCKET clientSocket = connectionSlot->getSocketId(); if(Socket::isSocketValid(&clientSocket) == true) { socketTriggeredList[clientSocket] = false; } - //else if(this->getGameHasBeenInitiated() == true && - // this->getAllowInGameConnections() == true) { - // socketTriggeredList[clientSocket] = false; - //} } } } void ServerInterface::validateConnectedClients() { - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - ConnectionSlot* connectionSlot = slots[i]; + for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); + ConnectionSlot* connectionSlot = slots[index]; if(connectionSlot != NULL) { connectionSlot->validateConnection(); } @@ -893,9 +910,9 @@ void ServerInterface::signalClientsToRecieveData(std::map masterController.signalSlaves(&eventList); } else { - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - ConnectionSlot* connectionSlot = slots[i]; + for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); + ConnectionSlot *connectionSlot = slots[index]; if(connectionSlot != NULL) { bool socketTriggered = false; @@ -903,16 +920,11 @@ void ServerInterface::signalClientsToRecieveData(std::map if(Socket::isSocketValid(&clientSocket)) { socketTriggered = socketTriggeredList[clientSocket]; } - //else if(this->getGameHasBeenInitiated() == true && - // this->getAllowInGameConnections() == true) { - //socketTriggeredList[clientSocket] = true; - //socketTriggered = socketTriggeredList[clientSocket]; - //} - ConnectionSlotEvent &event = eventList[i]; - bool socketSignalled = signalClientReceiveCommands(connectionSlot,i,socketTriggered,event); + ConnectionSlotEvent &event = eventList[index]; + bool socketSignalled = signalClientReceiveCommands(connectionSlot,index,socketTriggered,event); if(connectionSlot != NULL && socketTriggered == true) { - mapSlotSignalledList[i] = socketSignalled; + mapSlotSignalledList[index] = socketSignalled; } } } @@ -927,7 +939,6 @@ void ServerInterface::checkForCompletedClients(std::map & mapSlotSigna const bool newThreadManager = Config::getInstance().getBool("EnableNewThreadManager","false"); if(newThreadManager == true) { - //printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); //bool slavesCompleted = masterController.waitTillSlavesTrigger(1000 * MAX_SLOT_THREAD_WAIT_TIME); masterController.waitTillSlavesTrigger(1000 * MAX_SLOT_THREAD_WAIT_TIME); @@ -970,24 +981,23 @@ void ServerInterface::checkForCompletedClients(std::map & mapSlotSigna for(bool threadsDone = false; exitServer == false && threadsDone == false && difftime((long int)time(NULL),waitForThreadElapsed) < MAX_SLOT_THREAD_WAIT_TIME;) { + threadsDone = true; // Examine all threads for completion of delegation - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - + for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { //printf("===> START slot %d [%p] - About to checkForCompletedClients\n",i,slots[i]); - - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); //printf("===> IN slot %d - About to checkForCompletedClients\n",i); - ConnectionSlot* connectionSlot = slots[i]; - if(connectionSlot != NULL && connectionSlot->isConnected() == true && - mapSlotSignalledList[i] == true && + ConnectionSlot* connectionSlot = slots[index]; + if(connectionSlot != NULL && + connectionSlot->isConnected() == true && + mapSlotSignalledList[index] == true && connectionSlot->getJoinGameInProgress() == false && - slotsCompleted.find(i) == slotsCompleted.end()) { + slotsCompleted.find(index) == slotsCompleted.end()) { + try { - - std::vector errorList = connectionSlot->getThreadErrorList(); // Collect any collected errors from threads if(errorList.empty() == false) { @@ -1001,13 +1011,13 @@ void ServerInterface::checkForCompletedClients(std::map & mapSlotSigna } // Not done waiting for data yet - bool updateFinished = (connectionSlot != NULL ? connectionSlot->updateCompleted(&eventList[i]) : true); + bool updateFinished = (connectionSlot != NULL ? connectionSlot->updateCompleted(&eventList[index]) : true); if(updateFinished == false) { threadsDone = false; break; } else { - slotsCompleted[i] = true; + slotsCompleted[index] = true; } } catch(const exception &ex) { @@ -1017,7 +1027,6 @@ void ServerInterface::checkForCompletedClients(std::map & mapSlotSigna errorMsgList.push_back(ex.what()); } } - //printf("===> END slot %d - About to checkForCompletedClients\n",i); } } @@ -1031,27 +1040,30 @@ void ServerInterface::checkForLaggingClients(std::map &mapSlotSignalle std::vector &errorMsgList) { bool lastGlobalLagCheckTimeUpdate = false; if(gameHasBeenInitiated == true) { + time_t waitForClientsElapsed = time(NULL); time_t waitForThreadElapsed = time(NULL); std::map slotsCompleted; std::map slotsWarnedList; + for(bool threadsDone = false; exitServer == false && threadsDone == false && difftime((long int)time(NULL),waitForThreadElapsed) < MAX_SLOT_THREAD_WAIT_TIME;) { + threadsDone = true; // Examine all threads for completion of delegation - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { + for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { //printf("#1 Check lag for i: %d\n",i); - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - ConnectionSlot* connectionSlot = slots[i]; + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); + ConnectionSlot* connectionSlot = slots[index]; + if(connectionSlot != NULL && connectionSlot->isConnected() == true && - connectionSlot->getSkipLagCheck() == false && - mapSlotSignalledList[i] == true && - slotsCompleted.find(i) == slotsCompleted.end()) { + connectionSlot->getSkipLagCheck() == false && + mapSlotSignalledList[index] == true && + slotsCompleted.find(index) == slotsCompleted.end()) { //printf("#2 Check lag for i: %d playerindex: %d name [%s] socket: %d\n",i,connectionSlot->getPlayerIndex(),connectionSlot->getName().c_str(),connectionSlot->getSocketId()); - try { std::vector errorList = connectionSlot->getThreadErrorList(); // Show any collected errors from threads @@ -1066,7 +1078,7 @@ void ServerInterface::checkForLaggingClients(std::map &mapSlotSignalle } // Not done waiting for data yet - bool updateFinished = (connectionSlot != NULL ? connectionSlot->updateCompleted(&eventList[i]) : true); + bool updateFinished = (connectionSlot != NULL ? connectionSlot->updateCompleted(&eventList[index]) : true); if(updateFinished == false) { //printf("#2a Check lag for i: %d\n",i); threadsDone = false; @@ -1077,19 +1089,19 @@ void ServerInterface::checkForLaggingClients(std::map &mapSlotSignalle std::pair clientLagExceededOrWarned = std::make_pair(false,false); if( gameHasBeenInitiated == true && connectionSlot != NULL && connectionSlot->isConnected() == true) { - clientLagExceededOrWarned = clientLagCheck(connectionSlot,slotsWarnedList[i]); + clientLagExceededOrWarned = clientLagCheck(connectionSlot,slotsWarnedList[index]); if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] clientLagExceededOrWarned.first = %d, clientLagExceededOrWarned.second = %d, gameSettings.getNetworkPauseGameForLaggedClients() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,clientLagExceededOrWarned.first,clientLagExceededOrWarned.second,gameSettings.getNetworkPauseGameForLaggedClients()); if(clientLagExceededOrWarned.first == true) { - slotsWarnedList[i] = true; + slotsWarnedList[index] = true; } } // If the client has exceeded lag and the server wants // to pause while they catch up, re-trigger the // client reader thread - if((clientLagExceededOrWarned.first == true && gameSettings.getNetworkPauseGameForLaggedClients() == true)) { // || - //(clientLagExceededOrWarned.second == true && slotsWarnedAndRetried[i] == false)) { + if((clientLagExceededOrWarned.first == true && + gameSettings.getNetworkPauseGameForLaggedClients() == true)) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d, clientLagExceededOrWarned.first = %d, clientLagExceededOrWarned.second = %d, difftime(time(NULL),waitForClientsElapsed) = %.2f, MAX_CLIENT_WAIT_SECONDS_FOR_PAUSE = %.2f\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,clientLagExceededOrWarned.first,clientLagExceededOrWarned.second,difftime((long int)time(NULL),waitForClientsElapsed),MAX_CLIENT_WAIT_SECONDS_FOR_PAUSE); @@ -1102,17 +1114,15 @@ void ServerInterface::checkForLaggingClients(std::map &mapSlotSignalle if(clientSocket > 0) { socketTriggered = socketTriggeredList[clientSocket]; } - ConnectionSlotEvent &event = eventList[i]; - mapSlotSignalledList[i] = signalClientReceiveCommands(connectionSlot,i,socketTriggered,event); - - //printf("#2b Check lag for i: %d\n",i); - threadsDone = false; + ConnectionSlotEvent &event = eventList[index]; + mapSlotSignalledList[index] = signalClientReceiveCommands(connectionSlot,index,socketTriggered,event); + threadsDone = false; } if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d, clientLagExceededOrWarned.first = %d, clientLagExceededOrWarned.second = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,clientLagExceededOrWarned.first,clientLagExceededOrWarned.second); } } else { - slotsCompleted[i] = true; + slotsCompleted[index] = true; } } } @@ -1124,9 +1134,9 @@ void ServerInterface::checkForLaggingClients(std::map &mapSlotSignalle } //printf("#3 Check lag for i: %d\n",i); - - if(connectionSlot != NULL && connectionSlot->isConnected() == true && - connectionSlot->getSkipLagCheck() == false) { + if(connectionSlot != NULL && + connectionSlot->isConnected() == true && + connectionSlot->getSkipLagCheck() == false) { //printf("#4 Check lag for i: %d\n",i); try { @@ -1142,19 +1152,20 @@ void ServerInterface::checkForLaggingClients(std::map &mapSlotSignalle //printf("\n\n\n^^^^^^^^^^^^^^ PART B\n\n\n"); lastGlobalLagCheckTimeUpdate = true; - clientLagExceededOrWarned = clientLagCheck(connectionSlot,slotsWarnedList[i]); + clientLagExceededOrWarned = clientLagCheck(connectionSlot,slotsWarnedList[index]); if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] clientLagExceededOrWarned.first = %d, clientLagExceededOrWarned.second = %d, gameSettings.getNetworkPauseGameForLaggedClients() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,clientLagExceededOrWarned.first,clientLagExceededOrWarned.second,gameSettings.getNetworkPauseGameForLaggedClients()); if(clientLagExceededOrWarned.first == true) { - slotsWarnedList[i] = true; + slotsWarnedList[index] = true; } // If the client has exceeded lag and the server wants // to pause while they catch up, re-trigger the // client reader thread if((clientLagExceededOrWarned.first == true && - gameSettings.getNetworkPauseGameForLaggedClients() == true)) { + gameSettings.getNetworkPauseGameForLaggedClients() == true)) { + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d, clientLagExceededOrWarned.first = %d, clientLagExceededOrWarned.second = %d, difftime(time(NULL),waitForClientsElapsed) = %.2f, MAX_CLIENT_WAIT_SECONDS_FOR_PAUSE = %.2f\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,clientLagExceededOrWarned.first,clientLagExceededOrWarned.second,difftime((long int)time(NULL),waitForClientsElapsed),MAX_CLIENT_WAIT_SECONDS_FOR_PAUSE); if(difftime((long int)time(NULL),waitForClientsElapsed) < MAX_CLIENT_WAIT_SECONDS_FOR_PAUSE) { @@ -1184,9 +1195,9 @@ void ServerInterface::checkForLaggingClients(std::map &mapSlotSignalle void ServerInterface::executeNetworkCommandsFromClients() { if(gameHasBeenInitiated == true) { - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - ConnectionSlot* connectionSlot= slots[i]; + for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); + ConnectionSlot* connectionSlot= slots[index]; if(connectionSlot != NULL && connectionSlot->isConnected() == true) { vector pendingList = connectionSlot->getPendingNetworkCommandList(true); if(pendingList.empty() == false) { @@ -1194,8 +1205,7 @@ void ServerInterface::executeNetworkCommandsFromClients() { NetworkCommand &cmd = pendingList[idx]; this->requestCommand(&cmd); } - - //printf("Executed: %d commands from slot: %d\n",pendingList.size(),i); + //printf("Executed: %d commands from slot: %d\n",pendingList.size(),index); } } } @@ -1203,17 +1213,20 @@ void ServerInterface::executeNetworkCommandsFromClients() { } void ServerInterface::dispatchPendingChatMessages(std::vector &errorMsgList) { - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - ConnectionSlot* connectionSlot= slots[i]; + for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { + + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); + ConnectionSlot *connectionSlot = slots[index]; + if(connectionSlot != NULL && connectionSlot->getChatTextList(false).empty() == false) { try { std::vector chatText = connectionSlot->getChatTextList(true); for(int chatIdx = 0; - exitServer == false && slots[i] != NULL && + exitServer == false && slots[index] != NULL && chatIdx < (int)chatText.size(); chatIdx++) { - connectionSlot= slots[i]; + + connectionSlot = slots[index]; if(connectionSlot != NULL) { ChatMsgInfo msg(chatText[chatIdx]); this->addChatInfo(msg); @@ -1225,20 +1238,22 @@ void ServerInterface::dispatchPendingChatMessages(std::vector &errorMsg if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] #1 about to broadcast nmtText chatText [%s] chatTeamIndex = %d, newChatPlayerIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,newChatText.c_str(),newChatTeamIndex,newChatPlayerIndex); - if(newChatLanguage == "" || newChatLanguage == connectionSlot->getNetworkPlayerLanguage()) { + if(newChatLanguage == "" || + newChatLanguage == connectionSlot->getNetworkPlayerLanguage()) { + NetworkMessageText networkMessageText(newChatText.c_str(),newChatTeamIndex,newChatPlayerIndex,newChatLanguage); - broadcastMessage(&networkMessageText, connectionSlot->getPlayerIndex(),i); + broadcastMessage(&networkMessageText, connectionSlot->getPlayerIndex(),index); } if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] after broadcast nmtText chatText [%s] chatTeamIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,newChatText.c_str(),newChatTeamIndex); } } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] i = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i); + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] index = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,index); // Its possible that the slot is disconnected here // so check the original pointer again - if(slots[i] != NULL) { - slots[i]->clearChatInfo(); + if(slots[index] != NULL) { + slots[index]->clearChatInfo(); } } catch(const exception &ex) { @@ -1251,33 +1266,36 @@ void ServerInterface::dispatchPendingChatMessages(std::vector &errorMsg } void ServerInterface::dispatchPendingMarkCellMessages(std::vector &errorMsgList) { - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - ConnectionSlot* connectionSlot= slots[i]; + for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { + + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); + ConnectionSlot* connectionSlot= slots[index]; + if(connectionSlot != NULL && connectionSlot->getMarkedCellList(false).empty() == false) { + try { std::vector chatText = connectionSlot->getMarkedCellList(true); for(int chatIdx = 0; - exitServer == false && slots[i] != NULL && + exitServer == false && slots[index] != NULL && chatIdx < (int)chatText.size(); chatIdx++) { - connectionSlot= slots[i]; + + connectionSlot= slots[index]; if(connectionSlot != NULL) { MarkedCell msg(chatText[chatIdx]); this->addMarkedCell(msg); NetworkMessageMarkCell networkMessageMarkCell(msg.getTargetPos(),msg.getFactionIndex(),msg.getNote(),msg.getPlayerIndex()); - broadcastMessage(&networkMessageMarkCell, connectionSlot->getPlayerIndex(),i); - + broadcastMessage(&networkMessageMarkCell, connectionSlot->getPlayerIndex(),index); //if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] after broadcast nmtText chatText [%s] chatTeamIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,newChatText.c_str(),newChatTeamIndex); } } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] i = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i); + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] i = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,index); // Its possible that the slot is disconnected here // so check the original pointer again - if(slots[i] != NULL) { - slots[i]->clearMarkedCellList(); + if(slots[index] != NULL) { + slots[index]->clearMarkedCellList(); } } catch(const exception &ex) { @@ -1289,31 +1307,34 @@ void ServerInterface::dispatchPendingMarkCellMessages(std::vector &erro } } void ServerInterface::dispatchPendingHighlightCellMessages(std::vector &errorMsgList) { - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - ConnectionSlot* connectionSlot= slots[i]; + for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { + + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); + ConnectionSlot* connectionSlot= slots[index]; if(connectionSlot != NULL && connectionSlot->getHighlightedCellList(false).empty() == false) { + try { std::vector highlightedCells = connectionSlot->getHighlightedCellList(true); for(int chatIdx = 0; - exitServer == false && slots[i] != NULL && + exitServer == false && slots[index] != NULL && chatIdx < (int)highlightedCells.size(); chatIdx++) { - connectionSlot= slots[i]; + + connectionSlot= slots[index]; if(connectionSlot != NULL) { MarkedCell msg(highlightedCells[chatIdx]); this->setHighlightedCell(msg); NetworkMessageHighlightCell networkMessageHighlightCell(msg.getTargetPos(),msg.getFactionIndex()); - broadcastMessage(&networkMessageHighlightCell, connectionSlot->getPlayerIndex(),i); + broadcastMessage(&networkMessageHighlightCell, connectionSlot->getPlayerIndex(),index); } } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] i = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i); + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] index = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,index); // Its possible that the slot is disconnected here // so check the original pointer again - if(slots[i] != NULL) { - slots[i]->clearHighlightedCellList(); + if(slots[index] != NULL) { + slots[index]->clearHighlightedCellList(); } } catch(const exception &ex) { @@ -1326,33 +1347,35 @@ void ServerInterface::dispatchPendingHighlightCellMessages(std::vector } void ServerInterface::dispatchPendingUnMarkCellMessages(std::vector &errorMsgList) { - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - ConnectionSlot* connectionSlot= slots[i]; + for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { + + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); + ConnectionSlot* connectionSlot= slots[index]; if(connectionSlot != NULL && connectionSlot->getUnMarkedCellList(false).empty() == false) { + try { std::vector chatText = connectionSlot->getUnMarkedCellList(true); for(int chatIdx = 0; - exitServer == false && slots[i] != NULL && + exitServer == false && slots[index] != NULL && chatIdx < (int)chatText.size(); chatIdx++) { - connectionSlot= slots[i]; + + connectionSlot = slots[index]; if(connectionSlot != NULL) { UnMarkedCell msg(chatText[chatIdx]); this->addUnMarkedCell(msg); NetworkMessageUnMarkCell networkMessageMarkCell(msg.getTargetPos(),msg.getFactionIndex()); - broadcastMessage(&networkMessageMarkCell, connectionSlot->getPlayerIndex(),i); - + broadcastMessage(&networkMessageMarkCell, connectionSlot->getPlayerIndex(),index); //if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] after broadcast nmtText chatText [%s] chatTeamIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,newChatText.c_str(),newChatTeamIndex); } } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] i = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i); + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] i = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,index); // Its possible that the slot is disconnected here // so check the original pointer again - if(slots[i] != NULL) { - slots[i]->clearUnMarkedCellList(); + if(slots[index] != NULL) { + slots[index]->clearUnMarkedCellList(); } } catch(const exception &ex) { @@ -1365,10 +1388,6 @@ void ServerInterface::dispatchPendingUnMarkCellMessages(std::vector &er } void ServerInterface::update() { - bool miniDebugPerf = false; - Chrono chrono; - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled || miniDebugPerf) chrono.start(); - //printf("\nServerInterface::update -- A\n"); std::vector errorMsgList; @@ -1379,36 +1398,23 @@ void ServerInterface::update() { //printf("\nServerInterface::update -- B\n"); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - if(miniDebugPerf && chrono.getMillis() > 10) printf("In [%s::%s Line: %d] took " MG_I64_SPECIFIER " msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - processTextMessageQueue(); processBroadCastMessageQueue(); //printf("\nServerInterface::update -- C\n"); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - if(miniDebugPerf && chrono.getMillis() > 10) printf("In [%s::%s Line: %d] took " MG_I64_SPECIFIER " msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - std::map socketTriggeredList; //update all slots updateSocketTriggeredList(socketTriggeredList); //printf("\nServerInterface::update -- D\n"); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - if(miniDebugPerf && chrono.getMillis() > 10) printf("In [%s::%s Line: %d] took " MG_I64_SPECIFIER " msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - if(gameHasBeenInitiated == false || - //this->getAllowInGameConnections() == true || socketTriggeredList.empty() == false) { //printf("\nServerInterface::update -- E\n"); - //printf("START Server update #1\n"); - std::map eventList; - //bool hasData = Socket::hasDataToRead(socketTriggeredList); bool hasData = false; if(gameHasBeenInitiated == false) { hasData = Socket::hasDataToRead(socketTriggeredList); @@ -1417,65 +1423,42 @@ void ServerInterface::update() { hasData = true; } + if(hasData && SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] hasData == true\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); - //if(this->getGameHasBeenInitiated() == true && - // this->getAllowInGameConnections() == true) { - //printf("Checking for new client connections socketTriggeredList.size(): %d hasData: %d\n",socketTriggeredList.size(),hasData); - //} - - if(hasData) if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] hasData == true\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - if(miniDebugPerf && chrono.getMillis() > 10) printf("In [%s::%s Line: %d] took " MG_I64_SPECIFIER " msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - - //if(gameHasBeenInitiated == false || hasData == true || this->getAllowInGameConnections() == true) { if(gameHasBeenInitiated == false || hasData == true) { //printf("START Server update #2\n"); - std::map mapSlotSignalledList; // Step #1 tell all connection slot worker threads to receive socket data if(gameHasBeenInitiated == false) signalClientsToRecieveData(socketTriggeredList, eventList, mapSlotSignalledList); if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] ============ Step #2\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - if(miniDebugPerf && chrono.getMillis() > 10) printf("In [%s::%s Line: %d] took " MG_I64_SPECIFIER " msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - //printf("START Server update #2\n"); - if(gameHasBeenInitiated == false || hasData == true) { - //printf("START Server update #3\n"); // Step #2 check all connection slot worker threads for completed status - if(gameHasBeenInitiated == false) checkForCompletedClients(mapSlotSignalledList,errorMsgList, eventList); + if(gameHasBeenInitiated == false) { + checkForCompletedClients(mapSlotSignalledList,errorMsgList, eventList); + } if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] ============ Step #3\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - if(miniDebugPerf && chrono.getMillis() > 10) printf("In [%s::%s Line: %d] took " MG_I64_SPECIFIER " msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - //printf("START Server update #4\n"); - //printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + // Step #3 check clients for any lagging scenarios and try to deal with them - if(gameHasBeenInitiated == false) checkForLaggingClients(mapSlotSignalledList, eventList, socketTriggeredList,errorMsgList); + if(gameHasBeenInitiated == false) { + checkForLaggingClients(mapSlotSignalledList, eventList, socketTriggeredList,errorMsgList); + } if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] ============ Step #4\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - if(miniDebugPerf && chrono.getMillis() > 10) printf("In [%s::%s Line: %d] took " MG_I64_SPECIFIER " msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - //printf("START Server update #5\n"); - //printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); // Step #4 dispatch network commands to the pending list so that they are done in proper order executeNetworkCommandsFromClients(); if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] ============ Step #5\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - if(miniDebugPerf && chrono.getMillis() > 10) printf("In [%s::%s Line: %d] took " MG_I64_SPECIFIER " msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - //printf("START Server update #6\n"); - //printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); // Step #5 dispatch pending chat messages dispatchPendingChatMessages(errorMsgList); @@ -1487,13 +1470,12 @@ void ServerInterface::update() { dispatchPendingHighlightCellMessages(errorMsgList); if(gameHasBeenInitiated == true && - difftime((long int)time(NULL),gameStartTime) >= LAG_CHECK_GRACE_PERIOD && - difftime((long int)time(NULL),lastGlobalLagCheckTime) >= LAG_CHECK_INTERVAL_PERIOD) { + difftime((long int)time(NULL),gameStartTime) >= LAG_CHECK_GRACE_PERIOD && + difftime((long int)time(NULL),lastGlobalLagCheckTime) >= LAG_CHECK_INTERVAL_PERIOD) { std::map mapSlotSignalledList; checkForLaggingClients(mapSlotSignalledList, eventList, socketTriggeredList,errorMsgList); } - //printf("START Server update #7\n"); } else if(gameHasBeenInitiated == true && @@ -1506,11 +1488,7 @@ void ServerInterface::update() { std::map mapSlotSignalledList; checkForLaggingClients(mapSlotSignalledList, eventList, socketTriggeredList,errorMsgList); } - //printf("START Server update #9\n"); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - if(miniDebugPerf && chrono.getMillis() > 10) printf("In [%s::%s Line: %d] took " MG_I64_SPECIFIER " msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); } else if(gameHasBeenInitiated == true && difftime((long int)time(NULL),gameStartTime) >= LAG_CHECK_GRACE_PERIOD && @@ -1522,18 +1500,13 @@ void ServerInterface::update() { std::map mapSlotSignalledList; checkForLaggingClients(mapSlotSignalledList, eventList, socketTriggeredList,errorMsgList); } - //printf("START Server update #11\n"); - - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - if(miniDebugPerf && chrono.getMillis() > 10) printf("In [%s::%s Line: %d] took " MG_I64_SPECIFIER " msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); } else if(gameHasBeenInitiated == true && difftime((long int)time(NULL),gameStartTime) >= LAG_CHECK_GRACE_PERIOD && difftime((long int)time(NULL),lastGlobalLagCheckTime) >= LAG_CHECK_INTERVAL_PERIOD) { //printf("\nServerInterface::update -- F\n"); - //printf("START Server update #12\n"); std::map eventList; @@ -1541,25 +1514,21 @@ void ServerInterface::update() { checkForLaggingClients(mapSlotSignalledList, eventList, socketTriggeredList,errorMsgList); } - //printf("START Server update #13\n"); - if(miniDebugPerf && chrono.getMillis() > 10) printf("In [%s::%s Line: %d] took " MG_I64_SPECIFIER " msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - // Check if we need to switch masterserver admin to a new player because original admin disconnected - if(gameHasBeenInitiated == true && this->gameSettings.getMasterserver_admin() > 0) { + if(gameHasBeenInitiated == true && + this->gameSettings.getMasterserver_admin() > 0) { - if(miniDebugPerf && chrono.getMillis() > 10) printf("In [%s::%s Line: %d] took " MG_I64_SPECIFIER " msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); - //!!! - bool foundAdminSlot = false; + bool foundAdminSlot = false; int iFirstConnectedSlot = -1; - for(int i= 0; i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - if(slots[i] != NULL && slots[i]->isConnected() == true) { + for(int index = 0; index < GameConstants::maxPlayers; ++index) { + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); + if(slots[index] != NULL && slots[index]->isConnected() == true) { if(iFirstConnectedSlot < 0) { - iFirstConnectedSlot = i; + iFirstConnectedSlot = index; } - if(this->gameSettings.getMasterserver_admin() == slots[i]->getSessionKey()) { + if(this->gameSettings.getMasterserver_admin() == slots[index]->getSessionKey()) { foundAdminSlot = true; break; } @@ -1583,15 +1552,11 @@ void ServerInterface::update() { } } //printf("\nServerInterface::update -- G\n"); - //printf("START Server update #14\n"); - if(miniDebugPerf && chrono.getMillis() > 10) printf("In [%s::%s Line: %d] took " MG_I64_SPECIFIER " msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); checkListenerSlots(); //printf("START Server update #15\n"); - - if(miniDebugPerf && chrono.getMillis() > 10) printf("In [%s::%s Line: %d] took " MG_I64_SPECIFIER " msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); } catch(const exception &ex) { //printf("\nServerInterface::update -- H\n"); @@ -1600,24 +1565,22 @@ void ServerInterface::update() { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] error detected [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); errorMsgList.push_back(ex.what()); } + if(errorMsgList.empty() == false){ - for(int iErrIdx = 0;iErrIdx < (int)errorMsgList.size();++iErrIdx){ - string & sErr = errorMsgList[iErrIdx]; - if(sErr != ""){ + for(int iErrIdx = 0; iErrIdx < (int)errorMsgList.size(); ++iErrIdx) { + string &sErr = errorMsgList[iErrIdx]; + if(sErr != "") { DisplayErrorMessage(sErr); } } } - //printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); } void ServerInterface::updateKeyframe(int frameCount) { - Chrono chrono; - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled) chrono.start(); currentFrameCount = frameCount; if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] currentFrameCount = %d, requestedCommands.size() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,currentFrameCount,requestedCommands.size()); + NetworkMessageCommandList networkMessageCommandList(frameCount); for(int index = 0; index < GameConstants::maxPlayers; ++index) { networkMessageCommandList.setNetworkPlayerFactionCRC(index,this->getNetworkPlayerFactionCRC(index)); @@ -1637,7 +1600,6 @@ void ServerInterface::updateKeyframe(int frameCount) { // Possible cause of out of synch since we have more commands that need // to be sent in this frame if(requestedCommands.empty() == false) { - //char szBuf[1024]=""; if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] WARNING / ERROR, requestedCommands.size() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,requestedCommands.size()); SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] WARNING / ERROR, requestedCommands.size() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,requestedCommands.size()); @@ -1645,8 +1607,6 @@ void ServerInterface::updateKeyframe(int frameCount) { sendTextMessage(sMsg,-1, true,""); } - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] build command list took %lld msecs, networkMessageCommandList.getCommandCount() = %d, frameCount = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis(),networkMessageCommandList.getCommandCount(),frameCount); - //broadcast commands //printf("START Server send currentFrameCount = %d\n",currentFrameCount); @@ -1659,10 +1619,10 @@ void ServerInterface::updateKeyframe(int frameCount) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] error detected [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,ex.what()); DisplayErrorMessage(ex.what()); } - if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] broadcastMessage took %lld msecs, networkMessageCommandList.getCommandCount() = %d, frameCount = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis(),networkMessageCommandList.getCommandCount(),frameCount); } -bool ServerInterface::shouldDiscardNetworkMessage(NetworkMessageType networkMessageType, ConnectionSlot *connectionSlot) { +bool ServerInterface::shouldDiscardNetworkMessage(NetworkMessageType networkMessageType, + ConnectionSlot *connectionSlot) { bool discard = false; if(connectionSlot != NULL) { switch(networkMessageType) { @@ -1841,38 +1801,46 @@ void ServerInterface::waitUntilReady(Checksum *checksum) { logger.setCancelLoadingEnabled(true); } - Lang &lang= Lang::getInstance(); - uint64 waitLoopIterationCount = 0; - uint64 MAX_LOOP_COUNT_BEFORE_SLEEP = 10; - MAX_LOOP_COUNT_BEFORE_SLEEP = Config::getInstance().getInt("NetworkServerLoopGameLoadingCap",intToStr(MAX_LOOP_COUNT_BEFORE_SLEEP).c_str()); + Lang &lang = Lang::getInstance(); + uint64 waitLoopIterationCount = 0; + uint64 MAX_LOOP_COUNT_BEFORE_SLEEP = 10; + MAX_LOOP_COUNT_BEFORE_SLEEP = Config::getInstance().getInt("NetworkServerLoopGameLoadingCap",intToStr(MAX_LOOP_COUNT_BEFORE_SLEEP).c_str()); if(MAX_LOOP_COUNT_BEFORE_SLEEP == 0) { MAX_LOOP_COUNT_BEFORE_SLEEP = 1; } - int sleepMillis = Config::getInstance().getInt("NetworkServerLoopGameLoadingCapSleepMillis","10"); + int sleepMillis = Config::getInstance().getInt("NetworkServerLoopGameLoadingCapSleepMillis","10"); + int64 lastStatusUpdate = 0; - int64 lastStatusUpdate = 0; + while(exitServer == false && + allReady == false && + logger.getCancelLoading() == false) { - while(exitServer == false && allReady == false && logger.getCancelLoading() == false) { waitLoopIterationCount++; - if(waitLoopIterationCount > 0 && waitLoopIterationCount % MAX_LOOP_COUNT_BEFORE_SLEEP == 0) { + if(waitLoopIterationCount > 0 && + waitLoopIterationCount % MAX_LOOP_COUNT_BEFORE_SLEEP == 0) { + sleep(sleepMillis); waitLoopIterationCount = 0; } vector waitingForHosts; allReady= true; - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - ConnectionSlot* connectionSlot= slots[i]; + for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { + + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); + ConnectionSlot* connectionSlot= slots[index]; if(connectionSlot != NULL && connectionSlot->isConnected() == true) { if(connectionSlot->isReady() == false) { + NetworkMessageType networkMessageType= connectionSlot->getNextMessageType(); // consume old messages from the lobby bool discarded = shouldDiscardNetworkMessage(networkMessageType,connectionSlot); if(discarded == false) { + NetworkMessageReady networkMessageReady; if(networkMessageType == nmtReady && connectionSlot->receiveMessage(&networkMessageReady)) { + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s] networkMessageType==nmtReady\n",__FUNCTION__); connectionSlot->setReady(); @@ -1880,14 +1848,13 @@ void ServerInterface::waitUntilReady(Checksum *checksum) { } else if(networkMessageType != nmtInvalid) { string sErr = "Unexpected network message: " + intToStr(networkMessageType); - sendTextMessage(sErr,-1, true,"",i); + sendTextMessage(sErr,-1, true,"",index); DisplayErrorMessage(sErr); logger.setCancelLoading(false); return; } } waitingForHosts.push_back(connectionSlot->getName()); - allReady= false; } } @@ -1898,13 +1865,13 @@ void ServerInterface::waitUntilReady(Checksum *checksum) { if(chrono.getMillis() > readyWaitTimeout) { Lang &lang= Lang::getInstance(); const vector languageList = this->gameSettings.getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { + for(unsigned int langIndex = 0; langIndex < languageList.size(); ++langIndex) { string sErr = "Timeout waiting for clients."; if(lang.hasString("TimeoutWaitingForClients") == true) { - sErr = lang.getString("TimeoutWaitingForClients",languageList[i]); + sErr = lang.getString("TimeoutWaitingForClients",languageList[langIndex]); } - bool localEcho = lang.isLanguageLocal(languageList[i]); - sendTextMessage(sErr,-1, localEcho, languageList[i]); + bool localEcho = lang.isLanguageLocal(languageList[langIndex]); + sendTextMessage(sErr,-1, localEcho, languageList[langIndex]); if(localEcho == true) { DisplayErrorMessage(sErr); } @@ -1913,28 +1880,31 @@ void ServerInterface::waitUntilReady(Checksum *checksum) { return; } else { - //if(chrono.getMillis() % 100 == 0) { if(chrono.getMillis() - lastStatusUpdate > 200) { lastStatusUpdate = chrono.getMillis(); string waitForHosts = ""; - for(int i = 0; i < (int)waitingForHosts.size(); i++) { + for(int hostIndex = 0; hostIndex < (int)waitingForHosts.size(); hostIndex++) { if(waitForHosts != "") { waitForHosts += ", "; } - waitForHosts += waitingForHosts[i]; + waitForHosts += waitingForHosts[hostIndex]; } char szBuf[8096]=""; string updateTextFormat = lang.getString("NetworkGameServerLoadStatus"); - if(updateTextFormat == "" || updateTextFormat[0] == '?') { + if(updateTextFormat == "" || + updateTextFormat[0] == '?') { + updateTextFormat = "Waiting for network: %lld seconds elapsed (maximum wait time: %d seconds)"; } snprintf(szBuf,8096,updateTextFormat.c_str(),(long long int)(chrono.getMillis() / 1000),int(readyWaitTimeout / 1000)); char szBuf1[8096]=""; string statusTextFormat = lang.getString("NetworkGameStatusWaiting"); - if(statusTextFormat == "" || statusTextFormat[0] == '?') { + if(statusTextFormat == "" || + statusTextFormat[0] == '?') { + statusTextFormat = "Waiting for players: %s"; } snprintf(szBuf1,8096,statusTextFormat.c_str(),waitForHosts.c_str()); @@ -1943,11 +1913,11 @@ void ServerInterface::waitUntilReady(Checksum *checksum) { uint32 loadingStatus = nmls_NONE; //send ready message after, so clients start delayed - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - ConnectionSlot* connectionSlot= slots[i]; + for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[slotIndex],CODE_AT_LINE_X(slotIndex)); + ConnectionSlot *connectionSlot= slots[slotIndex]; if(connectionSlot != NULL && connectionSlot->isConnected() == true) { - switch(i) { + switch(slotIndex) { case 0: loadingStatus |= nmls_PLAYER1_CONNECTED; if(connectionSlot->isReady()) { @@ -2001,9 +1971,9 @@ void ServerInterface::waitUntilReady(Checksum *checksum) { } // send loading status message - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - ConnectionSlot* connectionSlot= slots[i]; + for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[slotIndex],CODE_AT_LINE_X(slotIndex)); + ConnectionSlot* connectionSlot= slots[slotIndex]; if(connectionSlot != NULL && connectionSlot->isConnected() == true) { NetworkMessageLoadingStatus networkMessageLoadingStatus(loadingStatus); connectionSlot->sendMessage(&networkMessageLoadingStatus); @@ -2021,17 +1991,17 @@ void ServerInterface::waitUntilReady(Checksum *checksum) { if(logger.getCancelLoading() == true) { Lang &lang= Lang::getInstance(); const vector languageList = this->gameSettings.getUniqueNetworkPlayerLanguages(); - for(unsigned int i = 0; i < languageList.size(); ++i) { - string sErr = lang.getString("GameCancelledByUser",languageList[i]); - bool localEcho = lang.isLanguageLocal(languageList[i]); - sendTextMessage(sErr,-1, localEcho,languageList[i]); + for(unsigned int langIndex = 0; langIndex < languageList.size(); ++langIndex) { + + string sErr = lang.getString("GameCancelledByUser",languageList[langIndex]); + bool localEcho = lang.isLanguageLocal(languageList[langIndex]); + sendTextMessage(sErr,-1, localEcho,languageList[langIndex]); + if(localEcho == true) { DisplayErrorMessage(sErr); } } quitGame(true); - - //DisplayErrorMessage(sErr); logger.setCancelLoading(false); return; } @@ -2039,13 +2009,13 @@ void ServerInterface::waitUntilReady(Checksum *checksum) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s] PART B (telling client we are ready!\n",__FUNCTION__); try { //send ready message after, so clients start delayed - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - ConnectionSlot* connectionSlot= slots[i]; + for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { + + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[slotIndex],CODE_AT_LINE_X(slotIndex)); + ConnectionSlot* connectionSlot= slots[slotIndex]; if(connectionSlot != NULL && connectionSlot->isConnected() == true) { NetworkMessageReady networkMessageReady(checksum->getSum()); connectionSlot->sendMessage(&networkMessageReady); - connectionSlot->setGameStarted(true); } } @@ -2064,22 +2034,22 @@ void ServerInterface::processBroadCastMessageQueue() { MutexSafeWrapper safeMutexSlot(broadcastMessageQueueThreadAccessor,CODE_AT_LINE); if(broadcastMessageQueue.empty() == false) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] broadcastMessageQueue.size() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,broadcastMessageQueue.size()); - for(int i = 0; i < (int)broadcastMessageQueue.size(); ++i) { - pair &item = broadcastMessageQueue[i]; - if(item.first != NULL) { - this->broadcastMessage(item.first,item.second); - delete item.first; + for(int index = 0; index < (int)broadcastMessageQueue.size(); ++index) { + pair &item = broadcastMessageQueue[index]; + if(item.first != NULL) { + this->broadcastMessage(item.first,item.second); + delete item.first; + } + item.first = NULL; } - item.first = NULL; + broadcastMessageQueue.clear(); } - broadcastMessageQueue.clear(); -} } void ServerInterface::queueBroadcastMessage(NetworkMessage *networkMessage, int excludeSlot) { MutexSafeWrapper safeMutexSlot(broadcastMessageQueueThreadAccessor,CODE_AT_LINE); pair item; - item.first = networkMessage; + item.first = networkMessage; item.second = excludeSlot; broadcastMessageQueue.push_back(item); } @@ -2088,8 +2058,8 @@ void ServerInterface::processTextMessageQueue() { MutexSafeWrapper safeMutexSlot(textMessageQueueThreadAccessor,CODE_AT_LINE); if(textMessageQueue.empty() == false) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] textMessageQueue.size() = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,textMessageQueue.size()); - for(int i = 0; i < (int)textMessageQueue.size(); ++i) { - TextMessageQueue &item = textMessageQueue[i]; + for(int index = 0; index < (int)textMessageQueue.size(); ++index) { + TextMessageQueue &item = textMessageQueue[index]; sendTextMessage(item.text, item.teamIndex, item.echoLocal, item.targetLanguage); } textMessageQueue.clear(); @@ -2098,14 +2068,13 @@ void ServerInterface::processTextMessageQueue() { void ServerInterface::queueTextMessage(const string & text, int teamIndex, bool echoLocal, string targetLanguage) { - //printf("Line: %d text [%s]\n",__LINE__,text.c_str()); MutexSafeWrapper safeMutexSlot(textMessageQueueThreadAccessor,CODE_AT_LINE); TextMessageQueue item; - item.text = text; - item.teamIndex = teamIndex; - item.echoLocal = echoLocal; + item.text = text; + item.teamIndex = teamIndex; + item.echoLocal = echoLocal; item.targetLanguage = targetLanguage; textMessageQueue.push_back(item); } @@ -2118,15 +2087,15 @@ void ServerInterface::sendTextMessage(const string & text, int teamIndex, void ServerInterface::sendTextMessage(const string& text, int teamIndex, bool echoLocal, string targetLanguage, int lockedSlotIndex) { //printf("Line: %d text [%s] echoLocal = %d\n",__LINE__,text.c_str(),echoLocal); - //assert(text.length() > 0); if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] text [%s] teamIndex = %d, echoLocal = %d, lockedSlotIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,text.c_str(),teamIndex,echoLocal,lockedSlotIndex); + NetworkMessageText networkMessageText(text, teamIndex, getHumanPlayerIndex(), targetLanguage); broadcastMessage(&networkMessageText, -1, lockedSlotIndex); + if(echoLocal == true) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - //ChatMsgInfo msg(text.c_str(),networkMessageText.getSender().c_str(),teamIndex,networkMessageText.getPlayerIndex()); ChatMsgInfo msg(text.c_str(),teamIndex,networkMessageText.getPlayerIndex(), targetLanguage); this->addChatInfo(msg); } @@ -2138,12 +2107,9 @@ void ServerInterface::sendMarkCellMessage(Vec2i targetPos, int factionIndex, str } void ServerInterface::sendMarkCellMessage(Vec2i targetPos, int factionIndex, string note, int playerIndex, int lockedSlotIndex) { - //printf("Line: %d text [%s] echoLocal = %d\n",__LINE__,text.c_str(),echoLocal); - //assert(text.length() > 0); - - //if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] text [%s] teamIndex = %d, echoLocal = %d, lockedSlotIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,text.c_str(),teamIndex,echoLocal,lockedSlotIndex); NetworkMessageMarkCell networkMessageMarkCell(targetPos,factionIndex, note, playerIndex); broadcastMessage(&networkMessageMarkCell, -1, lockedSlotIndex); + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); } @@ -2152,44 +2118,40 @@ void ServerInterface::sendHighlightCellMessage(Vec2i targetPos, int factionIndex } void ServerInterface::sendHighlightCellMessage(Vec2i targetPos, int factionIndex, int lockedSlotIndex) { - //printf("Line: %d echoLocal = %d\n",__LINE__,echoLocal); - - //if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] teamIndex = %d, echoLocal = %d, lockedSlotIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,teamIndex,echoLocal,lockedSlotIndex); NetworkMessageHighlightCell networkMessageHighlightCell(targetPos,factionIndex); broadcastMessage(&networkMessageHighlightCell, -1, lockedSlotIndex); + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); } - void ServerInterface::sendUnMarkCellMessage(Vec2i targetPos, int factionIndex) { sendUnMarkCellMessage(targetPos, factionIndex, -1); } void ServerInterface::sendUnMarkCellMessage(Vec2i targetPos, int factionIndex, int lockedSlotIndex) { - //printf("Line: %d text [%s] echoLocal = %d\n",__LINE__,text.c_str(),echoLocal); - //assert(text.length() > 0); - - //if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] text [%s] teamIndex = %d, echoLocal = %d, lockedSlotIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,text.c_str(),teamIndex,echoLocal,lockedSlotIndex); NetworkMessageUnMarkCell networkMessageMarkCell(targetPos,factionIndex); broadcastMessage(&networkMessageMarkCell, -1, lockedSlotIndex); + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); } void ServerInterface::quitGame(bool userManuallyQuit) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + NetworkMessageQuit networkMessageQuit; broadcastMessage(&networkMessageQuit); + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); } string ServerInterface::getNetworkStatus() { Lang &lang = Lang::getInstance(); - string str=""; - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - ConnectionSlot* connectionSlot= slots[i]; + string str = ""; + for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); + ConnectionSlot *connectionSlot= slots[index]; - str+= intToStr(i)+ ": "; + str += intToStr(index)+ ": "; if(connectionSlot!= NULL) { if(connectionSlot->isConnected()) { @@ -2202,24 +2164,29 @@ string ServerInterface::getNetworkStatus() { } } else { - str+= lang.getString("NotConnected"); + str += lang.getString("NotConnected"); } - str+= '\n'; + str += '\n'; } return str; } bool ServerInterface::launchGame(const GameSettings *gameSettings) { bool bOkToStart = true; + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - ConnectionSlot *connectionSlot= slots[i]; + + for(int index = 0; exitServer == false && index < GameConstants::maxPlayers; ++index) { + + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); + ConnectionSlot *connectionSlot= slots[index]; if(connectionSlot != NULL && (connectionSlot->getAllowDownloadDataSynch() == true || connectionSlot->getAllowGameDataSynchCheck() == true) && connectionSlot->isConnected()) { + if(connectionSlot->getNetworkGameDataSynchCheckOk() == false) { + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] map [%d] tile [%d] techtree [%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,connectionSlot->getNetworkGameDataSynchCheckOkMap(),connectionSlot->getNetworkGameDataSynchCheckOkTile(),connectionSlot->getNetworkGameDataSynchCheckOkTech()); if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] map [%d] tile [%d] techtree [%d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,connectionSlot->getNetworkGameDataSynchCheckOkMap(),connectionSlot->getNetworkGameDataSynchCheckOkTile(),connectionSlot->getNetworkGameDataSynchCheckOkTech()); @@ -2232,33 +2199,38 @@ bool ServerInterface::launchGame(const GameSettings *gameSettings) { bool useInGameBlockingClientSockets = Config::getInstance().getBool("EnableInGameBlockingSockets","true"); if(useInGameBlockingClientSockets == true) { + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - for(int i= 0; i < GameConstants::maxPlayers; ++i) { - //int factionIndex = gameSettings->getFactionIndexForStartLocation(i); - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - ConnectionSlot *connectionSlot= slots[i]; + + for(int index = 0; index < GameConstants::maxPlayers; ++index) { + + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(index)); + ConnectionSlot *connectionSlot= slots[index]; if(connectionSlot != NULL && connectionSlot->isConnected()) { connectionSlot->getSocket()->setBlock(true); } } } - bool requiresUPNPTrigger = false; if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - for(int i= 0; i < GameConstants::maxPlayers; ++i) { - int factionIndex = gameSettings->getFactionIndexForStartLocation(i); - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - ConnectionSlot *connectionSlot= slots[i]; + + bool requiresUPNPTrigger = false; + for(int startIndex = 0; startIndex < GameConstants::maxPlayers; ++startIndex) { + + int factionIndex = gameSettings->getFactionIndexForStartLocation(startIndex); + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[startIndex],CODE_AT_LINE_X(startIndex)); + ConnectionSlot *connectionSlot= slots[startIndex]; if((connectionSlot == NULL || connectionSlot->isConnected() == false) && this->getAllowInGameConnections() == true) { + // Open slots for joining in progress game if(gameSettings->getFactionControl(factionIndex) != ctClosed && gameSettings->getFactionControl(factionIndex) != ctHuman) { //printf("Opening slot for in game connections for slot: %d, faction: %d\n",i,factionIndex); if(connectionSlot == NULL) { - addSlot(i); - connectionSlot = slots[i]; + addSlot(startIndex); + connectionSlot = slots[startIndex]; requiresUPNPTrigger = true; } connectionSlot->setCanAcceptConnections(true); @@ -2295,7 +2267,9 @@ bool ServerInterface::launchGame(const GameSettings *gameSettings) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] needToRepublishToMasterserver = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,needToRepublishToMasterserver); if(publishToMasterserverThread == NULL) { - if(needToRepublishToMasterserver == true || GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + if(needToRepublishToMasterserver == true || + GlobalStaticFlags::getIsNonGraphicalModeEnabled() == true) { + static string mutexOwnerId = string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + intToStr(__LINE__); publishToMasterserverThread = new SimpleTaskThread(this,0,125); publishToMasterserverThread->setUniqueID(mutexOwnerId); @@ -2316,6 +2290,7 @@ bool ServerInterface::launchGame(const GameSettings *gameSettings) { gameLaunched = true; } if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + return bOkToStart; } @@ -2328,25 +2303,29 @@ void ServerInterface::shutdownFTPServer() { } void ServerInterface::checkListenerSlots() { - if(gameLaunched == true && this->getAllowInGameConnections() == true) { + if(gameLaunched == true && + this->getAllowInGameConnections() == true) { + if(difftime((long int)time(NULL),lastListenerSlotCheckTime) >= 7) { - lastListenerSlotCheckTime = time(NULL); + + lastListenerSlotCheckTime = time(NULL); bool useInGameBlockingClientSockets = Config::getInstance().getBool("EnableInGameBlockingSockets","true"); if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - for(int i= 0; i < GameConstants::maxPlayers; ++i) { - int factionIndex = gameSettings.getFactionIndexForStartLocation(i); + for(int startIndex = 0; startIndex < GameConstants::maxPlayers; ++startIndex) { + + int factionIndex = gameSettings.getFactionIndexForStartLocation(startIndex); if(gameSettings.getFactionControl(factionIndex) != ctClosed && gameSettings.getFactionControl(factionIndex) != ctHuman) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - ConnectionSlot *connectionSlot= slots[i]; + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[startIndex],CODE_AT_LINE_X(startIndex)); + ConnectionSlot *connectionSlot= slots[startIndex]; // Open slots for joining in progress game if(connectionSlot == NULL) { - printf("Opening slot for in game connections, slot: %d, factionindex: %d name: %s\n",i,factionIndex,gameSettings.getFactionTypeName(factionIndex).c_str()); + printf("Opening slot for in game connections, slot: %d, factionindex: %d name: %s\n",startIndex,factionIndex,gameSettings.getFactionTypeName(factionIndex).c_str()); - addSlot(i); - connectionSlot = slots[i]; + addSlot(startIndex); + connectionSlot = slots[startIndex]; if(useInGameBlockingClientSockets == true) { connectionSlot->getSocket()->setBlock(true); } @@ -2355,9 +2334,9 @@ void ServerInterface::checkListenerSlots() { else if(connectionSlot != NULL && connectionSlot->getCanAcceptConnections() == false && connectionSlot->isConnected() == false) { - printf("Removing slot for in game connections, slot: %d, factionindex: %d name: %s\n",i,factionIndex,gameSettings.getFactionTypeName(factionIndex).c_str()); + printf("Removing slot for in game connections, slot: %d, factionindex: %d name: %s\n",startIndex,factionIndex,gameSettings.getFactionTypeName(factionIndex).c_str()); - this->removeSlot(i); + this->removeSlot(startIndex); } } } @@ -2372,23 +2351,28 @@ void ServerInterface::broadcastGameSetup(GameSettings *gameSettingsBuffer, bool if(gameSettingsBuffer == NULL) { throw megaglest_runtime_error("gameSettingsBuffer == NULL"); } - for(unsigned int i = 0; i < (unsigned int)gameSettingsBuffer->getFactionCount(); ++i) { - int slotIndex = gameSettingsBuffer->getStartLocationIndex(i); - if(gameSettingsBuffer->getFactionControl(i) == ctNetwork && + for(unsigned int factionIndex = 0; factionIndex < (unsigned int)gameSettingsBuffer->getFactionCount(); ++factionIndex) { + + int slotIndex = gameSettingsBuffer->getStartLocationIndex(factionIndex); + if(gameSettingsBuffer->getFactionControl(factionIndex) == ctNetwork && isClientConnected(slotIndex) == false) { - gameSettingsBuffer->setNetworkPlayerName(i,GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME); + + gameSettingsBuffer->setNetworkPlayerName(factionIndex,GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME); } } if(setGameSettingsBuffer == true) { validateGameSettings(gameSettingsBuffer); - //setGameSettings(gameSettingsBuffer,false); - MutexSafeWrapper safeMutex(serverSynchAccessor,CODE_AT_LINE); + } + + MutexSafeWrapper safeMutex(serverSynchAccessor,CODE_AT_LINE); + if(setGameSettingsBuffer == true) { gameSettings = *gameSettingsBuffer; gameSettingsUpdateCount++; } - MutexSafeWrapper safeMutex(serverSynchAccessor,CODE_AT_LINE); + NetworkMessageLaunch networkMessageLaunch(gameSettingsBuffer, nmtBroadCastSetup); broadcastMessage(&networkMessageLaunch); + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); } @@ -2397,7 +2381,9 @@ void ServerInterface::broadcastMessage(NetworkMessage *networkMessage, int exclu if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); MutexSafeWrapper safeMutexSlotBroadCastAccessor(inBroadcastMessageThreadAccessor,CODE_AT_LINE); - if(inBroadcastMessage == true && dynamic_cast(networkMessage) != NULL) { + if(inBroadcastMessage == true && + dynamic_cast(networkMessage) != NULL) { + safeMutexSlotBroadCastAccessor.ReleaseLock(); NetworkMessageText *txtMsg = dynamic_cast(networkMessage); if(txtMsg != NULL) { @@ -2411,47 +2397,48 @@ void ServerInterface::broadcastMessage(NetworkMessage *networkMessage, int exclu safeMutexSlotBroadCastAccessor.ReleaseLock(true); } - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(NULL,CODE_AT_LINE_X(i)); - if(i != lockedSlotIndex) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] i = %d, lockedSlotIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i,lockedSlotIndex); - safeMutexSlot.setMutex(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); + for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { + MutexSafeWrapper safeMutexSlot(NULL,CODE_AT_LINE_X(slotIndex)); + if(slotIndex != lockedSlotIndex) { + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] i = %d, lockedSlotIndex = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,slotIndex,lockedSlotIndex); + safeMutexSlot.setMutex(slotAccessorMutexes[slotIndex],CODE_AT_LINE_X(slotIndex)); } - ConnectionSlot* connectionSlot= slots[i]; + ConnectionSlot* connectionSlot= slots[slotIndex]; - if(i != excludeSlot && connectionSlot != NULL) { + if(slotIndex != excludeSlot && connectionSlot != NULL) { if(connectionSlot->isConnected()) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] before sendMessage\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); + connectionSlot->sendMessage(networkMessage); + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] after sendMessage\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); } if(gameHasBeenInitiated == true && connectionSlot->isConnected() == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] #1 before removeSlot for slot# %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i); - //safeMutexSlot.ReleaseLock(); + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] #1 before removeSlot for slot# %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,slotIndex); if(this->getAllowInGameConnections() == false) { - //printf("Removing connection slot from broadcastMessage #1!\n"); - removeSlot(i,i); + removeSlot(slotIndex,slotIndex); } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] #1 after removeSlot for slot# %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i); + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] #1 after removeSlot for slot# %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,slotIndex); } } - else if(i == excludeSlot && gameHasBeenInitiated == true && + else if(slotIndex == excludeSlot && gameHasBeenInitiated == true && connectionSlot != NULL && connectionSlot->isConnected() == false) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] #2 before removeSlot for slot# %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i); - //safeMutexSlot.ReleaseLock(); + + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] #2 before removeSlot for slot# %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,slotIndex); if(this->getAllowInGameConnections() == false) { - //printf("Removing connection slot from broadcastMessage #2!\n"); - removeSlot(i,i); + removeSlot(slotIndex,slotIndex); } - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] #2 after removeSlot for slot# %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,i); + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] #2 after removeSlot for slot# %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,slotIndex); } } safeMutexSlotBroadCastAccessor.Lock(); + inBroadcastMessage = false; + safeMutexSlotBroadCastAccessor.ReleaseLock(); } catch(const exception &ex) { @@ -2470,11 +2457,11 @@ void ServerInterface::broadcastMessage(NetworkMessage *networkMessage, int exclu void ServerInterface::broadcastMessageToConnectedClients(NetworkMessage *networkMessage, int excludeSlot) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); try { - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - ConnectionSlot *connectionSlot= slots[i]; + for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[slotIndex],CODE_AT_LINE_X(slotIndex)); + ConnectionSlot *connectionSlot= slots[slotIndex]; - if(i != excludeSlot && connectionSlot != NULL) { + if(slotIndex != excludeSlot && connectionSlot != NULL) { if(connectionSlot->isConnected()) { connectionSlot->sendMessage(networkMessage); } @@ -2490,38 +2477,28 @@ void ServerInterface::broadcastMessageToConnectedClients(NetworkMessage *network } void ServerInterface::updateListen() { - //if(this->getAllowInGameConnections() == true) { - //printf("updateListen() #1!\n"); - //} - if(gameHasBeenInitiated == true && this->getAllowInGameConnections() == false) { + if(gameHasBeenInitiated == true && + this->getAllowInGameConnections() == false) { return; } - //printf("updateListen() #1!\n"); - int openSlotCount = 0; - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - //MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],intToStr(__LINE__) + "_" + intToStr(i)); - bool isSlotOpen = (slots[i] != NULL && slots[i]->isConnected() == false); + for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { + bool isSlotOpen = (slots[slotIndex] != NULL && slots[slotIndex]->isConnected() == false); if(isSlotOpen == true) { ++openSlotCount; } } - //if(this->getAllowInGameConnections() == true) { - //printf("updateListen() #2: %d!\n",openSlotCount); - //} - serverSocket.listen(openSlotCount); } int ServerInterface::getOpenSlotCount() { int openSlotCount = 0; - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - //MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],intToStr(__LINE__) + "_" + intToStr(i)); - bool isSlotOpen = (slots[i] != NULL && slots[i]->isConnected() == false); + for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { + bool isSlotOpen = (slots[slotIndex] != NULL && slots[slotIndex]->isConnected() == false); if(isSlotOpen == true) { ++openSlotCount; } @@ -2530,74 +2507,73 @@ int ServerInterface::getOpenSlotCount() { } int ServerInterface::getGameSettingsUpdateCount() { - MutexSafeWrapper safeMutex(serverSynchAccessor,CODE_AT_LINE); if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] START gameSettingsUpdateCount = %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,gameSettingsUpdateCount); + MutexSafeWrapper safeMutex(serverSynchAccessor,CODE_AT_LINE); int result = gameSettingsUpdateCount; safeMutex.ReleaseLock(); return result; } void ServerInterface::validateGameSettings(GameSettings *serverGameSettings) { - MutexSafeWrapper safeMutex(serverSynchAccessor,CODE_AT_LINE); if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__); + MutexSafeWrapper safeMutex(serverSynchAccessor,CODE_AT_LINE); string mapFile = serverGameSettings->getMap(); - //bool useNext=false; printf("Trying to set map to [%s]. Current map is [%s]\n",serverGameSettings->getMap().c_str(),gameSettings.getMap().c_str()); if(find(mapFiles.begin(),mapFiles.end(),mapFile) == mapFiles.end()) { + printf("map not found on this server\n"); - int currentIndex=-1; - string currentMap=gameSettings.getMap(); - for (int i=0 ;i < (int)mapFiles.size(); i++) { - string current=mapFiles[i]; - if(current==currentMap) - { - currentIndex=i; + int currentIndex = -1; + string currentMap = gameSettings.getMap(); + for (int mapIndex = 0 ;mapIndex < (int)mapFiles.size(); ++mapIndex) { + string current = mapFiles[mapIndex]; + if(current == currentMap) { + currentIndex = mapIndex; break; } } - if(currentIndex==-1){ + if(currentIndex == -1) { serverGameSettings->setMap(gameSettings.getMap()); - } else { + } + else { if(mapFile>gameSettings.getMap()){ printf("mapFile>gameSettings [%s] > [%s]\n",mapFile.c_str(),gameSettings.getMap().c_str()); - int nextIndex=-1; - for (int i=0 ;i < (int)mapFiles.size(); i++) { - string current=mapFiles[i]; - if(current>mapFile) - { - nextIndex=i; + int nextIndex = -1; + for (int mapIndex = 0 ;mapIndex < (int)mapFiles.size(); ++mapIndex) { + string current = mapFiles[mapIndex]; + if(current > mapFile) { + nextIndex = mapIndex; break; } } - if(nextIndex>-1){ + if(nextIndex > -1) { serverGameSettings->setMap(mapFiles[nextIndex]); //printf("switch up\n"); - } else { + } + else { //printf("overflow top\n"); serverGameSettings->setMap(mapFiles[0]); } - } - else - { + else { printf("mapFile-1; i--) { - string current=mapFiles[i]; - if(current= 0; mapIndex--) { + string current = mapFiles[mapIndex]; + if(current < mapFile) { + nextIndex = mapIndex; break; } } - if(nextIndex>-1){ + if(nextIndex > -1) { serverGameSettings->setMap(mapFiles[nextIndex]); //printf("switch down\n"); - } else { + } + else { //printf("overflow bottom\n"); serverGameSettings->setMap(mapFiles[(mapFiles.size()-1)]); } @@ -2670,27 +2646,26 @@ void ServerInterface::setGameSettings(GameSettings *serverGameSettings, bool wai bool gotAckFromAllClients = false; while(gotAckFromAllClients == false && difftime((long int)time(NULL),tStart) <= 5) { gotAckFromAllClients = true; - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { + for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { //printf("===> START slot %d - About to setGameSettings #1\n",i); - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - ConnectionSlot *connectionSlot = slots[i]; + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[slotIndex],CODE_AT_LINE_X(slotIndex)); + ConnectionSlot *connectionSlot = slots[slotIndex]; if(connectionSlot != NULL && connectionSlot->isConnected()) { if(connectionSlot->getReceivedNetworkGameStatus() == false) { gotAckFromAllClients = false; } - connectionSlot->update(true,i); + connectionSlot->update(true,slotIndex); } - //printf("===> END slot %d - About to setGameSettings #1\n",i); } } } - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - ConnectionSlot *connectionSlot = slots[i]; + for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[slotIndex],CODE_AT_LINE_X(slotIndex)); + ConnectionSlot *connectionSlot = slots[slotIndex]; if(connectionSlot != NULL && connectionSlot->isConnected()) { connectionSlot->setReceivedNetworkGameStatus(false); } @@ -2706,20 +2681,19 @@ void ServerInterface::setGameSettings(GameSettings *serverGameSettings, bool wai bool gotAckFromAllClients = false; while(gotAckFromAllClients == false && difftime((long int)time(NULL),tStart) <= 5) { gotAckFromAllClients = true; - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - //printf("===> START slot %d - About to setGameSettings 2\n",i); + for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { + //printf("===> START slot %d - About to setGameSettings 2\n",slotIndex); - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - ConnectionSlot *connectionSlot = slots[i]; + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[slotIndex],CODE_AT_LINE_X(slotIndex)); + ConnectionSlot *connectionSlot = slots[slotIndex]; if(connectionSlot != NULL && connectionSlot->isConnected()) { if(connectionSlot->getReceivedNetworkGameStatus() == false) { gotAckFromAllClients = false; } - connectionSlot->update(true,i); + connectionSlot->update(true,slotIndex); } - - //printf("===> END slot %d - About to setGameSettings 2\n",i); + //printf("===> END slot %d - About to setGameSettings 2\n",slotIndex); } } } @@ -2766,25 +2740,25 @@ std::map ServerInterface::publishToMasterserver() { Config & config = Config::getInstance(); std::map < string, string > publishToServerInfo; if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - if(slots[i] != NULL) { + for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[slotIndex],CODE_AT_LINE_X(slotIndex)); + if(slots[slotIndex] != NULL) { slotCountUsed++; slotCountHumans++; - ConnectionSlot* connectionSlot= slots[i]; + ConnectionSlot* connectionSlot= slots[slotIndex]; if((connectionSlot!=NULL) && (connectionSlot->isConnected())) { slotCountConnectedPlayers++; } } } - publishToServerInfo["uuid"] = Config::getInstance().getString("PlayerId",""); - publishToServerInfo["glestVersion"] = glestVersionString; - publishToServerInfo["platform"] = getPlatformNameString() + "-" + getGITRevisionString(); - publishToServerInfo["binaryCompileDate"] = getCompileDateTime(); - publishToServerInfo["serverTitle"] = getHumanPlayerName() + "'s game"; - publishToServerInfo["tech"] = this->getGameSettings()->getTech(); - publishToServerInfo["map"] = this->getGameSettings()->getMap(); - publishToServerInfo["tileset"] = this->getGameSettings()->getTileset(); + publishToServerInfo["uuid"] = Config::getInstance().getString("PlayerId",""); + publishToServerInfo["glestVersion"] = glestVersionString; + publishToServerInfo["platform"] = getPlatformNameString() + "-" + getGITRevisionString(); + publishToServerInfo["binaryCompileDate"] = getCompileDateTime(); + publishToServerInfo["serverTitle"] = getHumanPlayerName() + "'s game"; + publishToServerInfo["tech"] = this->getGameSettings()->getTech(); + publishToServerInfo["map"] = this->getGameSettings()->getMap(); + publishToServerInfo["tileset"] = this->getGameSettings()->getTileset(); bool updateSlots = true; MutexSafeWrapper safeMutex2(gameStatsThreadAccessor,CODE_AT_LINE); @@ -2799,30 +2773,25 @@ std::map ServerInterface::publishToMasterserver() { safeMutex2.ReleaseLock(); if(updateSlots == true) { - publishToServerInfo["activeSlots"] = intToStr(slotCountUsed); - publishToServerInfo["networkSlots"] = intToStr(slotCountHumans); + publishToServerInfo["activeSlots"] = intToStr(slotCountUsed); + publishToServerInfo["networkSlots"] = intToStr(slotCountHumans); publishToServerInfo["connectedClients"] = intToStr(slotCountConnectedPlayers); } - string serverPort=config.getString("PortServer", intToStr(GameConstants::serverPort).c_str()); - string externalPort=config.getString("PortExternal", serverPort.c_str()); - publishToServerInfo["externalconnectport"] = externalPort; - publishToServerInfo["privacyPlease"] = intToStr(config.getBool("PrivacyPlease","false")); - publishToServerInfo["gameStatus"] = intToStr(game_status_in_progress); + string serverPort = config.getString("PortServer", intToStr(GameConstants::serverPort).c_str()); + string externalPort = config.getString("PortExternal", serverPort.c_str()); + publishToServerInfo["externalconnectport"] = externalPort; + publishToServerInfo["privacyPlease"] = intToStr(config.getBool("PrivacyPlease","false")); + publishToServerInfo["gameStatus"] = intToStr(game_status_in_progress); if(publishToMasterserverThread == NULL) { - publishToServerInfo["gameCmd"]= "gameOver"; - publishToServerInfo["gameStatus"] = intToStr(game_status_finished); + publishToServerInfo["gameCmd"] = "gameOver"; + publishToServerInfo["gameStatus"] = intToStr(game_status_finished); } //printf("Host game id = %s\n",this->getGameSettings()->getGameUUID().c_str()); publishToServerInfo["gameUUID"] = this->getGameSettings()->getGameUUID(); - //if(statsInterface != NULL) { - // - //} - // !!! - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); return publishToServerInfo; } @@ -2833,14 +2802,14 @@ std::map ServerInterface::publishToMasterserverStats() { MutexSafeWrapper safeMutex(gameStatsThreadAccessor,CODE_AT_LINE); std::map < string, string > publishToServerInfo; if(gameStats != NULL) { - publishToServerInfo["gameUUID"] = this->getGameSettings()->getGameUUID(); - publishToServerInfo["tech"] = this->getGameSettings()->getTech(); - publishToServerInfo["factionCount"] = intToStr(gameStats->getFactionCount()); - publishToServerInfo["framesPlayed"] = intToStr(gameStats->getFramesPlayed()); - publishToServerInfo["framesToCalculatePlaytime"] = intToStr(gameStats->getFramesToCalculatePlaytime()); - publishToServerInfo["maxConcurrentUnitCount"] = intToStr(gameStats->getMaxConcurrentUnitCount()); - publishToServerInfo["totalEndGameConcurrentUnitCount"] = intToStr(gameStats->getTotalEndGameConcurrentUnitCount()); - publishToServerInfo["isHeadlessServer"] = intToStr(gameStats->getIsMasterserverMode()); + publishToServerInfo["gameUUID"] = this->getGameSettings()->getGameUUID(); + publishToServerInfo["tech"] = this->getGameSettings()->getTech(); + publishToServerInfo["factionCount"] = intToStr(gameStats->getFactionCount()); + publishToServerInfo["framesPlayed"] = intToStr(gameStats->getFramesPlayed()); + publishToServerInfo["framesToCalculatePlaytime"] = intToStr(gameStats->getFramesToCalculatePlaytime()); + publishToServerInfo["maxConcurrentUnitCount"] = intToStr(gameStats->getMaxConcurrentUnitCount()); + publishToServerInfo["totalEndGameConcurrentUnitCount"] = intToStr(gameStats->getTotalEndGameConcurrentUnitCount()); + publishToServerInfo["isHeadlessServer"] = intToStr(gameStats->getIsMasterserverMode()); for(int factionIndex = 0; factionIndex < gameStats->getFactionCount(); ++factionIndex) { publishToServerInfo["factionIndex_" + intToStr(factionIndex)] = intToStr(factionIndex); @@ -2989,25 +2958,28 @@ std::string ServerInterface::DumpStatsToLog(bool dumpToStringOnly) const { out << "=========================================" << std::endl; int connectedSlotCount = 0; - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - ConnectionSlot *slot = slots[i]; + for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { + + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[slotIndex],CODE_AT_LINE_X(slotIndex)); + ConnectionSlot *slot = slots[slotIndex]; if(slot != NULL) { + connectedSlotCount++; - out << "Network connection for index: " << i << std::endl; + out << "Network connection for index: " << slotIndex << std::endl; out << "------------------------------" << std::endl; out << "Connected: " << boolToStr(slot->isConnected()) << std::endl; out << "Handshake received: " << boolToStr(slot->getConnectHasHandshaked()) << std::endl; if(slot->isConnected() == true) { - time_t connectTime = slot->getConnectedTime(); - struct tm *loctime = localtime (&connectTime); - char szBuf[8096]=""; + + time_t connectTime = slot->getConnectedTime(); + struct tm *loctime = localtime (&connectTime); + char szBuf[8096] = ""; strftime(szBuf,100,"%Y-%m-%d %H:%M:%S",loctime); - const int HOURS_IN_DAY = 24; - const int MINUTES_IN_HOUR = 60; + const int HOURS_IN_DAY = 24; + const int MINUTES_IN_HOUR = 60; const int SECONDS_IN_MINUTE = 60; - int InSeconds = difftime((long int)time(NULL),slot->getConnectedTime()); + int InSeconds = difftime((long int)time(NULL),slot->getConnectedTime()); // compute seconds int seconds = InSeconds % SECONDS_IN_MINUTE ; // throw away seconds used in previous statement and convert to minutes @@ -3020,20 +2992,20 @@ std::string ServerInterface::DumpStatsToLog(bool dumpToStringOnly) const { // compute hours int hours = InHours % HOURS_IN_DAY ; - out << "Connected at: " << szBuf << std::endl; - out << "Connection duration: " << hours << " hours " << minutes << " minutes " << seconds << " seconds." << std::endl; - out << "Player Index: " << slot->getPlayerIndex() << std::endl; - out << "IP Address: " << slot->getIpAddress() << std::endl; - out << "Player name: " << slot->getName() << std::endl; - out << "Player uuid: " << slot->getUUID() << std::endl; - out << "Language: " << slot->getNetworkPlayerLanguage() << std::endl; - out << "Game Version: " << slot->getVersionString() << std::endl; - out << "Session id: " << slot->getSessionKey() << std::endl; - out << "Socket id: " << slot->getSocketId() << std::endl; + out << "Connected at: " << szBuf << std::endl; + out << "Connection duration: " << hours << " hours " << minutes << " minutes " << seconds << " seconds." << std::endl; + out << "Player Index: " << slot->getPlayerIndex() << std::endl; + out << "IP Address: " << slot->getIpAddress() << std::endl; + out << "Player name: " << slot->getName() << std::endl; + out << "Player uuid: " << slot->getUUID() << std::endl; + out << "Language: " << slot->getNetworkPlayerLanguage() << std::endl; + out << "Game Version: " << slot->getVersionString() << std::endl; + out << "Session id: " << slot->getSessionKey() << std::endl; + out << "Socket id: " << slot->getSocketId() << std::endl; } } } - out << "Total Slot Count: " << connectedSlotCount << std::endl; + out << "Total Slot Count: " << connectedSlotCount << std::endl; out << "=========================================" << std::endl; std::string result = out.str(); @@ -3064,7 +3036,6 @@ void ServerInterface::notifyBadClientConnectAttempt(string ipAddress) { if(badClientConnectIPList.find(ipAddress) == badClientConnectIPList.end()) { badClientConnectIPList[ipAddress] = make_pair(0,(long int)time(NULL)); - //printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); } pair &lastBadConnectionAttempt = badClientConnectIPList[ipAddress]; @@ -3074,42 +3045,35 @@ void ServerInterface::notifyBadClientConnectAttempt(string ipAddress) { bool addToBlockedClientsList = false; if(difftime((long int)time(NULL),lastBadConnectionAttempt.second) <= BLOCK_BAD_CLIENT_CONNECT_MAX_SECONDS) { - //printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); if(lastBadConnectionAttempt.first+1 > BLOCK_BAD_CLIENT_CONNECT_MAX_ATTEMPTS) { addToBlockedClientsList = true; - //printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); } } else { // Reset after x seconds lastBadConnectionAttempt.first = 0; - //printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); } - //printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if(this->getAllowInGameConnections() == true) { printf("notifyBadClientConnectAttempt() #1: %s!\n",ipAddress.c_str()); } if(addToBlockedClientsList == true) { serverSocket.addIPAddressToBlockedList(ipAddress); - //printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); } lastBadConnectionAttempt.first++; lastBadConnectionAttempt.second = time(NULL); - - //printf("In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); } bool ServerInterface::getStartInGameConnectionLaunch() { bool result = false; - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - if(slots[i] != NULL) { - MutexSafeWrapper safeMutex(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - ConnectionSlot *slot = slots[i]; + for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { + MutexSafeWrapper safeMutex(slotAccessorMutexes[slotIndex],CODE_AT_LINE_X(slotIndex)); + if(slots[slotIndex] != NULL) { + + ConnectionSlot *slot = slots[slotIndex]; if(slot->getStartInGameConnectionLaunch() == true) { result = true; break; @@ -3121,10 +3085,11 @@ bool ServerInterface::getStartInGameConnectionLaunch() { bool ServerInterface::getPauseForInGameConnection() { bool result = false; - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - if(slots[i] != NULL) { - MutexSafeWrapper safeMutex(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - ConnectionSlot *slot = slots[i]; + for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { + MutexSafeWrapper safeMutex(slotAccessorMutexes[slotIndex],CODE_AT_LINE_X(slotIndex)); + if(slots[slotIndex] != NULL) { + + ConnectionSlot *slot = slots[slotIndex]; if(slot->getPauseForInGameConnection() == true) { result = true; break; @@ -3135,12 +3100,12 @@ bool ServerInterface::getPauseForInGameConnection() { } bool ServerInterface::getUnPauseForInGameConnection() { - bool result = false; - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - if(slots[i] != NULL) { - MutexSafeWrapper safeMutex(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - ConnectionSlot *slot = slots[i]; + for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { + MutexSafeWrapper safeMutex(slotAccessorMutexes[slotIndex],CODE_AT_LINE_X(slotIndex)); + if(slots[slotIndex] != NULL) { + + ConnectionSlot *slot = slots[slotIndex]; if(slot->isConnected() == true) { if(slot->isReady() == true) { result = true; @@ -3165,15 +3130,19 @@ bool ServerInterface::getUnPauseForInGameConnection() { ConnectionSlot * ServerInterface::findSlotForUUID(string uuid, bool unConnectedOnly) { ConnectionSlot *result = NULL; if(uuid != "") { - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); - ConnectionSlot *connectionSlot= slots[i]; - if(connectionSlot!= NULL) { + for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { + + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[slotIndex],CODE_AT_LINE_X(slotIndex)); + ConnectionSlot *connectionSlot= slots[slotIndex]; + + if(connectionSlot != NULL) { if(connectionSlot->getUUID() == uuid) { if(unConnectedOnly == false || (unConnectedOnly == true && connectionSlot->isConnected() == false)) { + if(result == NULL || - (result->getConnectedTime() > connectionSlot->getConnectedTime())) + (result->getConnectedTime() > connectionSlot->getConnectedTime())) + result = connectionSlot; } } @@ -3187,13 +3156,13 @@ void ServerInterface::saveGame(XmlNode *rootNode) { std::map mapTagReplacements; XmlNode *serverInterfaceNode = rootNode->addChild("ServerInterface"); - for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - if(slots[i] != NULL) { - MutexSafeWrapper safeMutex(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); + for(int slotIndex = 0; exitServer == false && slotIndex < GameConstants::maxPlayers; ++slotIndex) { + MutexSafeWrapper safeMutex(slotAccessorMutexes[slotIndex],CODE_AT_LINE_X(slotIndex)); + if(slots[slotIndex] != NULL) { XmlNode *slotNode = serverInterfaceNode->addChild("Slot"); - ConnectionSlot *slot = slots[i]; + ConnectionSlot *slot = slots[slotIndex]; if(slot != NULL) { slotNode->addAttribute("isconnected",intToStr(slot->isConnected()), mapTagReplacements); slotNode->addAttribute("sessionkey",intToStr(slot->getSessionKey()), mapTagReplacements); diff --git a/source/shared_lib/sources/platform/posix/socket.cpp b/source/shared_lib/sources/platform/posix/socket.cpp index 8aa8f0c4a..e5d69e877 100644 --- a/source/shared_lib/sources/platform/posix/socket.cpp +++ b/source/shared_lib/sources/platform/posix/socket.cpp @@ -2943,7 +2943,8 @@ void BroadCastSocketThread::execute() { //#else // strncat(buff,port_string.c_str(),std::min((int)port_string.length(),100)); //#endif - snprintf(buff,1024,"%s:%s:%d",buff,ipList[idx1].c_str(),this->boundPort); + string buffCopy = buff; + snprintf(buff,1024,"%s:%s:%d",buffCopy.c_str(),ipList[idx1].c_str(),this->boundPort); } if(difftime((long int)time(NULL),elapsed) >= 1 && getQuitStatus() == false) {