MasterServerClient.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. //
  2. // Created by Keith Johnston on 4/16/16.
  3. //
  4. #include "MasterServerClient.h"
  5. #include "../Precompiled.h"
  6. #include "../IO/Log.h"
  7. #include "../Network/NetworkPriority.h"
  8. #include "../Network/Network.h"
  9. #include "../Core/Profiler.h"
  10. #include "../Network/NetworkEvents.h"
  11. #include <rapidjson/document.h>
  12. #include <rapidjson/stringbuffer.h>
  13. #include <rapidjson/prettywriter.h>
  14. namespace Atomic
  15. {
  16. MasterServerClient::MasterServerClient(Context *context) :
  17. readingMasterMessageLength(true),
  18. Object(context),
  19. udpSecondsTillRetry_(0.5f),
  20. connectToMasterState_(MASTER_NOT_CONNECTED),
  21. clientConnectToGameServerState_(GAME_NOT_CONNECTED),
  22. timeBetweenClientPunchThroughAttempts_(1.0),
  23. timeTillNextPunchThroughAttempt_(0.0),
  24. timeBetweenClientConnectAttempts_(1.0),
  25. timeTillNextClientConnectAttempt_(1.0),
  26. masterTCPConnection_(NULL),
  27. clientToServerSocket_(NULL)
  28. {
  29. }
  30. MasterServerClient::~MasterServerClient()
  31. {
  32. if (masterTCPConnection_)
  33. {
  34. masterTCPConnection_->Disconnect();
  35. }
  36. }
  37. void MasterServerClient::ConnectToMaster(const String &address, unsigned short port) {
  38. PROFILE(ConnectToMaster);
  39. if (connectToMasterState_ != MASTER_NOT_CONNECTED)
  40. {
  41. DisconnectFromMaster();
  42. }
  43. masterServerInfo_.address = address;
  44. masterServerInfo_.port = port;
  45. masterServerInfo_.isRegisteringServer = false;
  46. // We first make a TCP connection
  47. SetConnectToMasterState(MASTER_CONNECTING_TCP);
  48. }
  49. void MasterServerClient::DisconnectFromMaster()
  50. {
  51. masterTCPConnection_->Disconnect();
  52. masterUDPConnection_->Disconnect();
  53. SetConnectToMasterState(MASTER_NOT_CONNECTED);
  54. }
  55. void MasterServerClient::ConnectToMasterAndRegister(const String &address, unsigned short port, const String& serverName) {
  56. PROFILE(ConnectToMaster);
  57. if (connectToMasterState_ != MASTER_NOT_CONNECTED)
  58. {
  59. DisconnectFromMaster();
  60. }
  61. masterServerInfo_.address = address;
  62. masterServerInfo_.port = port;
  63. masterServerInfo_.serverName = serverName;
  64. masterServerInfo_.isRegisteringServer = true;
  65. // We first make a TCP connection
  66. SetConnectToMasterState(MASTER_CONNECTING_TCP);
  67. }
  68. void MasterServerClient::RequestServerListFromMaster()
  69. {
  70. SendMessageToMasterServer("{ \"cmd\": \"getServerList\" }");
  71. }
  72. void MasterServerClient::ConnectToServerViaMaster(const String &serverId,
  73. const String &internalAddress, unsigned short internalPort,
  74. const String &externalAddress, unsigned short externalPort,
  75. Scene* scene)
  76. {
  77. remoteGameServerInfo_.serverId = serverId;
  78. remoteGameServerInfo_.internalAddress = internalAddress;
  79. remoteGameServerInfo_.internalPort = internalPort;
  80. remoteGameServerInfo_.externalAddress = externalAddress;
  81. remoteGameServerInfo_.externalPort = externalPort;
  82. remoteGameServerInfo_.clientScene = scene;
  83. SetConnectToGameServerState(GAME_CONNECTING_INTERNAL_IP);
  84. }
  85. void MasterServerClient::RegisterServerWithMaster(const String &name)
  86. {
  87. // Get the internal IP and port
  88. kNet::EndPoint localEndPoint = masterTCPConnection_->LocalEndPoint();
  89. unsigned char* ip = localEndPoint.ip;
  90. char str[256];
  91. sprintf(str, "%d.%d.%d.%d", (unsigned int)ip[0], (unsigned int)ip[1], (unsigned int)ip[2], (unsigned int)ip[3]);
  92. Atomic::Network* network = GetSubsystem<Network>();
  93. unsigned int localPort = network->GetServerPort();
  94. String msg = String("{") +
  95. String("\"cmd\":") + String("\"registerServer\",") +
  96. String("\"internalIP\": \"") + String(str) + String("\", ") +
  97. String("\"internalPort\": ") + String(localPort) + String(", ") +
  98. String("\"id\":\"") + masterServerConnectionId_ + String("\", ") +
  99. String("\"serverName\":\"") + name + String("\"") +
  100. String("}");
  101. SendMessageToMasterServer(msg);
  102. }
  103. void MasterServerClient::SendMessageToMasterServer(const String& msg)
  104. {
  105. if (masterTCPConnection_)
  106. {
  107. String netString = String(msg.Length()) + ':' + msg;
  108. masterTCPConnection_->Send(netString.CString(), netString.Length());
  109. }
  110. else
  111. {
  112. LOGERROR("No master server connection. Cannot send message");
  113. }
  114. }
  115. void MasterServerClient::Update(float dt)
  116. {
  117. if (masterTCPConnection_==NULL)
  118. {
  119. return;
  120. }
  121. CheckForMessageFromMaster();
  122. ConnectToMasterUpdate(dt);
  123. ConnectToGameServerUpdate(dt);
  124. CheckForNatPunchThroughRequests(dt);
  125. }
  126. void MasterServerClient::CheckForNatPunchThroughRequests(float dt)
  127. {
  128. if (clientIdToPunchThroughSocketMap_.Size() > 0)
  129. {
  130. if (timeTillNextPunchThroughAttempt_ <= 0)
  131. {
  132. for (HashMap<String, kNet::Socket*>::Iterator i = clientIdToPunchThroughSocketMap_.Begin();
  133. i != clientIdToPunchThroughSocketMap_.End();)
  134. {
  135. Network* network = GetSubsystem<Network>();
  136. LOGINFO("Sending packet to client");
  137. kNet::Socket* s = i->second_;
  138. if (network->IsEndPointConnected(s->RemoteEndPoint()))
  139. {
  140. i = clientIdToPunchThroughSocketMap_.Erase(i);
  141. }
  142. else
  143. {
  144. s->Send("K",1);
  145. ++i;
  146. }
  147. }
  148. // Reset the timer
  149. timeTillNextPunchThroughAttempt_ = timeBetweenClientPunchThroughAttempts_;
  150. }
  151. timeTillNextPunchThroughAttempt_ -= dt;
  152. }
  153. // See if we need to still be trying to punch through from the client
  154. if (clientConnectToGameServerState_ == GAME_CONNECTING_EXTERNAL_IP &&
  155. clientToServerSocket_ != NULL && timeTillNextClientConnectAttempt_ <= 0)
  156. {
  157. Atomic::Network* network = GetSubsystem<Network>();
  158. if (!network->GetServerConnection() || !network->GetServerConnection()->IsConnected())
  159. {
  160. LOGINFO("Sending packet to server");
  161. clientToServerSocket_->Send("K",1);
  162. }
  163. timeTillNextClientConnectAttempt_ = timeBetweenClientConnectAttempts_;
  164. }
  165. timeTillNextClientConnectAttempt_ -= dt;
  166. }
  167. void MasterServerClient::CheckForMessageFromMaster()
  168. {
  169. kNet::OverlappedTransferBuffer *buf = masterTCPConnection_->BeginReceive();
  170. if (buf && buf->bytesContains > 0) {
  171. int n = 0;
  172. int totalBytes = buf->bytesContains;
  173. while (n < totalBytes) {
  174. char c = buf->buffer.buf[n++];
  175. // Are we still reading in the length?
  176. if (readingMasterMessageLength) {
  177. if (c == ':') {
  178. sscanf(masterMessageLengthStr.CString(), "%u" , &bytesRemainingInMasterServerMessage_);
  179. readingMasterMessageLength = false;
  180. LOGINFO("Message is " + String(bytesRemainingInMasterServerMessage_) + " long");
  181. }
  182. else {
  183. masterMessageLengthStr += c;
  184. }
  185. }
  186. else {
  187. // Are we reading in the string?
  188. masterMessageStr += c;
  189. bytesRemainingInMasterServerMessage_--;
  190. // Did we hit the end of the string?
  191. if (bytesRemainingInMasterServerMessage_ == 0) {
  192. HandleMasterServerMessage(masterMessageStr);
  193. readingMasterMessageLength = true;
  194. masterMessageLengthStr = "";
  195. masterMessageStr = "";
  196. }
  197. }
  198. }
  199. masterTCPConnection_->EndReceive(buf);
  200. }
  201. }
  202. void MasterServerClient::ConnectToMasterUpdate(float dt)
  203. {
  204. if (connectToMasterState_ == MASTER_NOT_CONNECTED ||
  205. connectToMasterState_ == MASTER_CONNECTION_FAILED)
  206. {
  207. return;
  208. }
  209. if (connectToMasterState_ == MASTER_CONNECTING_UDP)
  210. {
  211. if (udpConnectionSecondsRemaining_ <= 0)
  212. {
  213. connectToMasterState_ = MASTER_CONNECTION_FAILED;
  214. // TODO - emit error event
  215. return;
  216. }
  217. if (udpSecondsTillRetry_ <= 0)
  218. {
  219. String msg = "{ \"cmd\": \"registerUDPPort\", \"id\": \"" + masterServerConnectionId_ + "\"}";
  220. masterUDPConnection_->Send(msg.CString(), msg.Length());
  221. udpSecondsTillRetry_ = 0.5;
  222. }
  223. else
  224. {
  225. udpSecondsTillRetry_ -= dt;
  226. udpConnectionSecondsRemaining_ -= dt;
  227. }
  228. }
  229. }
  230. void MasterServerClient::SetConnectToMasterState(ConnectToMasterState state)
  231. {
  232. Atomic::Network* network = GetSubsystem<Network>();
  233. kNet::Network* kNetNetwork = network->GetKnetNetwork();
  234. if (connectToMasterState_ == MASTER_NOT_CONNECTED &&
  235. state == MASTER_CONNECTING_TCP)
  236. {
  237. masterTCPConnection_ = kNetNetwork->ConnectSocket(masterServerInfo_.address.CString(),
  238. masterServerInfo_.port, kNet::SocketOverTCP);
  239. if (!masterTCPConnection_)
  240. {
  241. SetConnectToMasterState(MASTER_CONNECTION_FAILED);
  242. }
  243. else
  244. {
  245. SendMessageToMasterServer("{ \"cmd\": \"connectRequest\" }");
  246. }
  247. }
  248. else if (connectToMasterState_ == MASTER_CONNECTING_TCP &&
  249. state == MASTER_CONNECTING_UDP)
  250. {
  251. Atomic::Network* network = GetSubsystem<Network>();
  252. kNet::Network* kNetNetwork = network->GetKnetNetwork();
  253. kNet::NetworkServer* server = kNetNetwork->GetServer().ptr();
  254. kNet::EndPoint masterEndPoint;
  255. sscanf(masterServerInfo_.address.CString(), "%hu.%hu.%hu.%hu",
  256. (unsigned short *) &masterEndPoint.ip[0],
  257. (unsigned short *) &masterEndPoint.ip[1],
  258. (unsigned short *) &masterEndPoint.ip[2],
  259. (unsigned short *) &masterEndPoint.ip[3]);
  260. masterEndPoint.port = masterServerInfo_.port;
  261. if (server)
  262. {
  263. std::vector < kNet::Socket * > listenSockets = kNetNetwork->GetServer()->ListenSockets();
  264. kNet::Socket *listenSocket = listenSockets[0];
  265. // Create a UDP and a TCP connection to the master server
  266. // UDP connection re-uses the same udp port we are listening on for the sever
  267. masterUDPConnection_ = new kNet::Socket(listenSocket->GetSocketHandle(),
  268. listenSocket->LocalEndPoint(),
  269. listenSocket->LocalAddress(), masterEndPoint, "",
  270. kNet::SocketOverUDP, kNet::ServerClientSocket, 1400);
  271. }
  272. else
  273. {
  274. masterUDPConnection_ = kNetNetwork->CreateUnconnectedUDPSocket(masterServerInfo_.address.CString(),
  275. masterServerInfo_.port);
  276. }
  277. }
  278. if (state == MASTER_CONNECTION_FAILED)
  279. {
  280. LOGERROR("Could not connect to master server");
  281. SendEvent(E_MASTERCONNECTIONFAILED);
  282. }
  283. if (state == MASTER_CONNECTED)
  284. {
  285. SendEvent(E_MASTERCONNECTIONREADY);
  286. }
  287. connectToMasterState_ = state;
  288. }
  289. void MasterServerClient::SetConnectToGameServerState(ClientConnectToGameServerState state)
  290. {
  291. if (clientConnectToGameServerState_ == GAME_NOT_CONNECTED &&
  292. state == GAME_CONNECTING_INTERNAL_IP)
  293. {
  294. kNet::EndPoint serverEndPoint;
  295. sscanf(remoteGameServerInfo_.internalAddress.CString(), "%hu.%hu.%hu.%hu",
  296. (unsigned short *) &serverEndPoint.ip[0],
  297. (unsigned short *) &serverEndPoint.ip[1],
  298. (unsigned short *) &serverEndPoint.ip[2],
  299. (unsigned short *) &serverEndPoint.ip[3]);
  300. serverEndPoint.port = remoteGameServerInfo_.internalPort;
  301. clientToServerSocket_ = new kNet::Socket(masterUDPConnection_->GetSocketHandle(),
  302. masterUDPConnection_->LocalEndPoint(),
  303. masterUDPConnection_->LocalAddress(), serverEndPoint, "",
  304. kNet::SocketOverUDP, kNet::ClientConnectionLessSocket, 1400);
  305. Atomic::Network* network = GetSubsystem<Network>();
  306. network->ConnectWithExistingSocket(clientToServerSocket_, remoteGameServerInfo_.clientScene);
  307. connectToGameServerSecondsRemaining_ = 5.0f;
  308. LOGINFO("Connecting to Game Server on Internal IP: " +
  309. remoteGameServerInfo_.internalAddress + ":" +
  310. String(remoteGameServerInfo_.internalPort));
  311. }
  312. else if (clientConnectToGameServerState_ == GAME_CONNECTING_INTERNAL_IP &&
  313. state == GAME_CONNECTING_EXTERNAL_IP)
  314. {
  315. // Ask the master server to tell the game server
  316. // we want to connect to it.
  317. String msg = String("{") +
  318. String("\"cmd\":") + String("\"requestIntroduction\",") +
  319. String("\"id\":\"") + masterServerConnectionId_ + String("\", ") +
  320. String("\"serverId\":\"") + remoteGameServerInfo_.serverId + String("\"") +
  321. String("}");
  322. SendMessageToMasterServer(msg);
  323. kNet::EndPoint serverEndPoint;
  324. sscanf(remoteGameServerInfo_.externalAddress.CString(), "%hu.%hu.%hu.%hu",
  325. (unsigned short *) &serverEndPoint.ip[0],
  326. (unsigned short *) &serverEndPoint.ip[1],
  327. (unsigned short *) &serverEndPoint.ip[2],
  328. (unsigned short *) &serverEndPoint.ip[3]);
  329. serverEndPoint.port = remoteGameServerInfo_.externalPort;
  330. clientToServerSocket_ = new kNet::Socket(masterUDPConnection_->GetSocketHandle(),
  331. masterUDPConnection_->LocalEndPoint(),
  332. masterUDPConnection_->LocalAddress(), serverEndPoint, "",
  333. kNet::SocketOverUDP, kNet::ClientConnectionLessSocket, 1400);
  334. Atomic::Network* network = GetSubsystem<Network>();
  335. network->ConnectWithExistingSocket(clientToServerSocket_, remoteGameServerInfo_.clientScene);
  336. connectToGameServerSecondsRemaining_ = 5.0f;
  337. LOGINFO("Connecting to Game Server on External IP: " +
  338. remoteGameServerInfo_.externalAddress + ":" +
  339. String(remoteGameServerInfo_.externalPort));
  340. }
  341. if (state == GAME_CONNECTION_FAILED)
  342. {
  343. SendEvent(E_CONNECTFAILED);
  344. }
  345. clientConnectToGameServerState_ = state;
  346. }
  347. void MasterServerClient::ConnectToGameServerUpdate(float dt)
  348. {
  349. if (clientConnectToGameServerState_ == GAME_NOT_CONNECTED ||
  350. clientConnectToGameServerState_ == GAME_CONNECTED ||
  351. clientConnectToGameServerState_ == GAME_CONNECTION_FAILED)
  352. {
  353. return;
  354. }
  355. Atomic::Network* network = GetSubsystem<Network>();
  356. // If we are connected then set the final state
  357. if (network->GetServerConnection() && network->GetServerConnection()->IsConnected())
  358. {
  359. if (clientConnectToGameServerState_ == GAME_CONNECTING_INTERNAL_IP)
  360. {
  361. LOGINFO("Successfully connected using internal IP");
  362. }
  363. else if (clientConnectToGameServerState_ == GAME_CONNECTING_EXTERNAL_IP)
  364. {
  365. LOGINFO("Successfully connected using external IP");
  366. }
  367. SetConnectToGameServerState(GAME_CONNECTED);
  368. return;
  369. }
  370. if (connectToGameServerSecondsRemaining_ <= 0)
  371. {
  372. if (clientConnectToGameServerState_ == GAME_CONNECTING_INTERNAL_IP)
  373. {
  374. LOGINFO("Unable to connect via internal IP, trying external IP");
  375. SetConnectToGameServerState(GAME_CONNECTING_EXTERNAL_IP);
  376. }
  377. else
  378. {
  379. SetConnectToGameServerState(GAME_CONNECTION_FAILED);
  380. }
  381. return;
  382. }
  383. connectToGameServerSecondsRemaining_ -= dt;
  384. }
  385. void MasterServerClient::HandleMasterServerMessage(const String &msg)
  386. {
  387. LOGINFO("Got master server message: " + msg);
  388. rapidjson::Document document;
  389. if (document.Parse<0>(msg.CString()).HasParseError())
  390. {
  391. LOGERROR("Could not parse JSON data from string");
  392. return;
  393. }
  394. String cmd = document["cmd"].GetString();
  395. bool sendEvent = false;
  396. if (cmd == "connectTCPSuccess")
  397. {
  398. udpSecondsTillRetry_ = 0;
  399. udpConnectionSecondsRemaining_ = 5.0;
  400. masterServerConnectionId_ = document["id"].GetString();
  401. // Now connect with UDP
  402. SetConnectToMasterState(MASTER_CONNECTING_UDP);
  403. LOGINFO("TCP Connected");
  404. }
  405. else if (cmd == "connectUDPSuccess")
  406. {
  407. SetConnectToMasterState(MASTER_CONNECTED);
  408. // Register server if needed
  409. if (masterServerInfo_.isRegisteringServer)
  410. {
  411. RegisterServerWithMaster(masterServerInfo_.serverName);
  412. }
  413. LOGINFO("UDP Connected");
  414. }
  415. else if (cmd == "sendPacketToClient")
  416. {
  417. String clientIP = document["clientIP"].GetString();
  418. int clientPort = document["clientPort"].GetInt();
  419. LOGINFO("Got request to send packet to client at "+clientIP+":"+String(clientPort));
  420. kNet::EndPoint clientEndPoint;
  421. sscanf(clientIP.CString(), "%hu.%hu.%hu.%hu",
  422. (unsigned short *) &clientEndPoint.ip[0],
  423. (unsigned short *) &clientEndPoint.ip[1],
  424. (unsigned short *) &clientEndPoint.ip[2],
  425. (unsigned short *) &clientEndPoint.ip[3]);
  426. clientEndPoint.port = clientPort;
  427. // Create a socket that goes out the same port we are listening on to the client.
  428. // This will be used until the client actually connects.
  429. kNet::Socket* s = new kNet::Socket(masterUDPConnection_->GetSocketHandle(),
  430. masterUDPConnection_->LocalEndPoint(),
  431. masterUDPConnection_->LocalAddress(), clientEndPoint, "",
  432. kNet::SocketOverUDP, kNet::ServerClientSocket, 1400);
  433. String clientId = document["clientId"].GetString();
  434. clientIdToPunchThroughSocketMap_.Insert(MakePair(clientId, s));
  435. }
  436. else if (cmd == "serverList")
  437. {
  438. sendEvent = true;
  439. }
  440. if (sendEvent)
  441. {
  442. using namespace NetworkMessage;
  443. VariantMap& eventData = GetEventDataMap();
  444. eventData[P_DATA] = msg;
  445. SendEvent(E_MASTERMESSAGE, eventData);
  446. }
  447. }
  448. }