Network.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. //
  2. // Copyright (c) 2008-2017 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Core/CoreEvents.h"
  25. #include "../Core/Profiler.h"
  26. #include "../Engine/EngineEvents.h"
  27. #include "../IO/FileSystem.h"
  28. #include "../Input/InputEvents.h"
  29. #include "../IO/IOEvents.h"
  30. #include "../IO/Log.h"
  31. #include "../IO/MemoryBuffer.h"
  32. #include "../Network/HttpRequest.h"
  33. #include "../Network/Network.h"
  34. #include "../Network/NetworkEvents.h"
  35. #include "../Network/NetworkPriority.h"
  36. #include "../Network/Protocol.h"
  37. #include "../Scene/Scene.h"
  38. // ATOMIC BEGIN
  39. #include <kNet/include/kNet.h>
  40. #include <kNet/include/kNet/EndPoint.h>
  41. // ATOMIC END
  42. #include "../DebugNew.h"
  43. namespace Atomic
  44. {
  45. static const int DEFAULT_UPDATE_FPS = 30;
  46. Network::Network(Context* context) :
  47. Object(context),
  48. updateFps_(DEFAULT_UPDATE_FPS),
  49. simulatedLatency_(0),
  50. simulatedPacketLoss_(0.0f),
  51. updateInterval_(1.0f / (float)DEFAULT_UPDATE_FPS),
  52. updateAcc_(0.0f),
  53. // ATOMIC BEGIN
  54. serverPort_(0xFFFF)
  55. // ATOMIC END
  56. {
  57. network_ = new kNet::Network();
  58. // Register Network library object factories
  59. RegisterNetworkLibrary(context_);
  60. SubscribeToEvent(E_BEGINFRAME, ATOMIC_HANDLER(Network, HandleBeginFrame));
  61. SubscribeToEvent(E_RENDERUPDATE, ATOMIC_HANDLER(Network, HandleRenderUpdate));
  62. // Blacklist remote events which are not to be allowed to be registered in any case
  63. blacklistedRemoteEvents_.Insert(E_CONSOLECOMMAND);
  64. blacklistedRemoteEvents_.Insert(E_LOGMESSAGE);
  65. blacklistedRemoteEvents_.Insert(E_BEGINFRAME);
  66. blacklistedRemoteEvents_.Insert(E_UPDATE);
  67. blacklistedRemoteEvents_.Insert(E_POSTUPDATE);
  68. blacklistedRemoteEvents_.Insert(E_RENDERUPDATE);
  69. blacklistedRemoteEvents_.Insert(E_ENDFRAME);
  70. blacklistedRemoteEvents_.Insert(E_MOUSEBUTTONDOWN);
  71. blacklistedRemoteEvents_.Insert(E_MOUSEBUTTONUP);
  72. blacklistedRemoteEvents_.Insert(E_MOUSEMOVE);
  73. blacklistedRemoteEvents_.Insert(E_MOUSEWHEEL);
  74. blacklistedRemoteEvents_.Insert(E_KEYDOWN);
  75. blacklistedRemoteEvents_.Insert(E_KEYUP);
  76. blacklistedRemoteEvents_.Insert(E_TEXTINPUT);
  77. blacklistedRemoteEvents_.Insert(E_JOYSTICKCONNECTED);
  78. blacklistedRemoteEvents_.Insert(E_JOYSTICKDISCONNECTED);
  79. blacklistedRemoteEvents_.Insert(E_JOYSTICKBUTTONDOWN);
  80. blacklistedRemoteEvents_.Insert(E_JOYSTICKBUTTONUP);
  81. blacklistedRemoteEvents_.Insert(E_JOYSTICKAXISMOVE);
  82. blacklistedRemoteEvents_.Insert(E_JOYSTICKHATMOVE);
  83. blacklistedRemoteEvents_.Insert(E_TOUCHBEGIN);
  84. blacklistedRemoteEvents_.Insert(E_TOUCHEND);
  85. blacklistedRemoteEvents_.Insert(E_TOUCHMOVE);
  86. blacklistedRemoteEvents_.Insert(E_GESTURERECORDED);
  87. blacklistedRemoteEvents_.Insert(E_GESTUREINPUT);
  88. blacklistedRemoteEvents_.Insert(E_MULTIGESTURE);
  89. blacklistedRemoteEvents_.Insert(E_DROPFILE);
  90. blacklistedRemoteEvents_.Insert(E_INPUTFOCUS);
  91. blacklistedRemoteEvents_.Insert(E_MOUSEVISIBLECHANGED);
  92. blacklistedRemoteEvents_.Insert(E_EXITREQUESTED);
  93. blacklistedRemoteEvents_.Insert(E_SERVERCONNECTED);
  94. blacklistedRemoteEvents_.Insert(E_SERVERDISCONNECTED);
  95. blacklistedRemoteEvents_.Insert(E_CONNECTFAILED);
  96. blacklistedRemoteEvents_.Insert(E_CLIENTCONNECTED);
  97. blacklistedRemoteEvents_.Insert(E_CLIENTDISCONNECTED);
  98. blacklistedRemoteEvents_.Insert(E_CLIENTIDENTITY);
  99. blacklistedRemoteEvents_.Insert(E_CLIENTSCENELOADED);
  100. blacklistedRemoteEvents_.Insert(E_NETWORKMESSAGE);
  101. blacklistedRemoteEvents_.Insert(E_NETWORKUPDATE);
  102. blacklistedRemoteEvents_.Insert(E_NETWORKUPDATESENT);
  103. blacklistedRemoteEvents_.Insert(E_NETWORKSCENELOADFAILED);
  104. }
  105. Network::~Network()
  106. {
  107. // If server connection exists, disconnect, but do not send an event because we are shutting down
  108. Disconnect(100);
  109. serverConnection_.Reset();
  110. clientConnections_.Clear();
  111. }
  112. void Network::HandleMessage(kNet::MessageConnection* source, kNet::packet_id_t packetId, kNet::message_id_t msgId, const char* data,
  113. size_t numBytes)
  114. {
  115. // Only process messages from known sources
  116. Connection* connection = GetConnection(source);
  117. if (connection)
  118. {
  119. MemoryBuffer msg(data, (unsigned)numBytes);
  120. if (connection->ProcessMessage((int)msgId, msg))
  121. return;
  122. // If message was not handled internally, forward as an event
  123. using namespace NetworkMessage;
  124. VariantMap& eventData = GetEventDataMap();
  125. eventData[P_CONNECTION] = connection;
  126. eventData[P_MESSAGEID] = (int)msgId;
  127. eventData[P_DATA].SetBuffer(msg.GetData(), msg.GetSize());
  128. connection->SendEvent(E_NETWORKMESSAGE, eventData);
  129. }
  130. else
  131. ATOMIC_LOGWARNING("Discarding message from unknown MessageConnection " + ToString((void*)source));
  132. }
  133. u32 Network::ComputeContentID(kNet::message_id_t msgId, const char* data, size_t numBytes)
  134. {
  135. switch (msgId)
  136. {
  137. case MSG_CONTROLS:
  138. // Return fixed content ID for controls
  139. return CONTROLS_CONTENT_ID;
  140. case MSG_NODELATESTDATA:
  141. case MSG_COMPONENTLATESTDATA:
  142. {
  143. // Return the node or component ID, which is first in the message
  144. MemoryBuffer msg(data, (unsigned)numBytes);
  145. return msg.ReadNetID();
  146. }
  147. default:
  148. // By default return no content ID
  149. return 0;
  150. }
  151. }
  152. void Network::NewConnectionEstablished(kNet::MessageConnection* connection)
  153. {
  154. connection->RegisterInboundMessageHandler(this);
  155. // Create a new client connection corresponding to this MessageConnection
  156. SharedPtr<Connection> newConnection(new Connection(context_, true, kNet::SharedPtr<kNet::MessageConnection>(connection)));
  157. newConnection->ConfigureNetworkSimulator(simulatedLatency_, simulatedPacketLoss_);
  158. clientConnections_[connection] = newConnection;
  159. ATOMIC_LOGINFO("Client " + newConnection->ToString() + " connected");
  160. using namespace ClientConnected;
  161. VariantMap& eventData = GetEventDataMap();
  162. eventData[P_CONNECTION] = newConnection;
  163. newConnection->SendEvent(E_CLIENTCONNECTED, eventData);
  164. }
  165. void Network::ClientDisconnected(kNet::MessageConnection* connection)
  166. {
  167. connection->Disconnect(0);
  168. // Remove the client connection that corresponds to this MessageConnection
  169. HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::Iterator i = clientConnections_.Find(connection);
  170. if (i != clientConnections_.End())
  171. {
  172. Connection* connection = i->second_;
  173. ATOMIC_LOGINFO("Client " + connection->ToString() + " disconnected");
  174. using namespace ClientDisconnected;
  175. VariantMap& eventData = GetEventDataMap();
  176. eventData[P_CONNECTION] = connection;
  177. connection->SendEvent(E_CLIENTDISCONNECTED, eventData);
  178. clientConnections_.Erase(i);
  179. }
  180. }
  181. bool Network::Connect(const String& address, unsigned short port, kNet::SocketTransportLayer transport, Scene* scene, const VariantMap& identity)
  182. {
  183. ATOMIC_PROFILE(Connect);
  184. // If a previous connection already exists, disconnect it and wait for some time for the connection to terminate
  185. if (serverConnection_)
  186. {
  187. serverConnection_->Disconnect(100);
  188. OnServerDisconnected();
  189. }
  190. kNet::SharedPtr<kNet::MessageConnection> connection = network_->Connect(address.CString(), port, transport, this);
  191. if (connection)
  192. {
  193. serverConnection_ = new Connection(context_, false, connection);
  194. serverConnection_->SetScene(scene);
  195. serverConnection_->SetIdentity(identity);
  196. serverConnection_->SetConnectPending(true);
  197. serverConnection_->ConfigureNetworkSimulator(simulatedLatency_, simulatedPacketLoss_);
  198. ATOMIC_LOGINFO("Connecting to server " + serverConnection_->ToString());
  199. return true;
  200. }
  201. else
  202. {
  203. ATOMIC_LOGERROR("Failed to connect to server " + address + ":" + String(port));
  204. SendEvent(E_CONNECTFAILED);
  205. return false;
  206. }
  207. }
  208. void Network::Disconnect(int waitMSec)
  209. {
  210. if (!serverConnection_)
  211. return;
  212. ATOMIC_PROFILE(Disconnect);
  213. serverConnection_->Disconnect(waitMSec);
  214. }
  215. bool Network::StartServer(unsigned short port, kNet::SocketTransportLayer transport)
  216. {
  217. if (IsServerRunning())
  218. return true;
  219. ATOMIC_PROFILE(StartServer);
  220. // ATOMIC BEGIN
  221. serverPort_ = port;
  222. // ATOMIC END
  223. if (network_->StartServer(port, transport, this, true) != 0)
  224. {
  225. ATOMIC_LOGINFOF("Started %s server on port %i", (transport == kNet::SocketOverTCP ? "TCP" : "UDP"), port);
  226. return true;
  227. }
  228. else
  229. {
  230. ATOMIC_LOGERRORF("Failed to start %s server on port %i", (transport == kNet::SocketOverTCP ? "TCP" : "UDP"), port);
  231. return false;
  232. }
  233. }
  234. void Network::StopServer()
  235. {
  236. if (!IsServerRunning())
  237. return;
  238. ATOMIC_PROFILE(StopServer);
  239. clientConnections_.Clear();
  240. network_->StopServer();
  241. ATOMIC_LOGINFO("Stopped server");
  242. }
  243. void Network::BroadcastMessage(int msgID, bool reliable, bool inOrder, const VectorBuffer& msg, unsigned contentID)
  244. {
  245. BroadcastMessage(msgID, reliable, inOrder, msg.GetData(), msg.GetSize(), contentID);
  246. }
  247. void Network::BroadcastMessage(int msgID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes,
  248. unsigned contentID)
  249. {
  250. // Make sure not to use kNet internal message ID's
  251. if (msgID <= 0x4 || msgID >= 0x3ffffffe)
  252. {
  253. ATOMIC_LOGERROR("Can not send message with reserved ID");
  254. return;
  255. }
  256. kNet::NetworkServer* server = network_->GetServer();
  257. if (server)
  258. server->BroadcastMessage((unsigned long)msgID, reliable, inOrder, 0, contentID, (const char*)data, numBytes);
  259. else
  260. ATOMIC_LOGERROR("Server not running, can not broadcast messages");
  261. }
  262. void Network::BroadcastRemoteEvent(StringHash eventType, bool inOrder, const VariantMap& eventData)
  263. {
  264. for (HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::Iterator i = clientConnections_.Begin();
  265. i != clientConnections_.End(); ++i)
  266. i->second_->SendRemoteEvent(eventType, inOrder, eventData);
  267. }
  268. void Network::BroadcastRemoteEvent(Scene* scene, StringHash eventType, bool inOrder, const VariantMap& eventData)
  269. {
  270. for (HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::Iterator i = clientConnections_.Begin();
  271. i != clientConnections_.End(); ++i)
  272. {
  273. if (i->second_->GetScene() == scene)
  274. i->second_->SendRemoteEvent(eventType, inOrder, eventData);
  275. }
  276. }
  277. void Network::BroadcastRemoteEvent(Node* node, StringHash eventType, bool inOrder, const VariantMap& eventData)
  278. {
  279. if (!node)
  280. {
  281. ATOMIC_LOGERROR("Null sender node for remote node event");
  282. return;
  283. }
  284. if (node->GetID() >= FIRST_LOCAL_ID)
  285. {
  286. ATOMIC_LOGERROR("Sender node has a local ID, can not send remote node event");
  287. return;
  288. }
  289. Scene* scene = node->GetScene();
  290. for (HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::Iterator i = clientConnections_.Begin();
  291. i != clientConnections_.End(); ++i)
  292. {
  293. if (i->second_->GetScene() == scene)
  294. i->second_->SendRemoteEvent(node, eventType, inOrder, eventData);
  295. }
  296. }
  297. void Network::SetUpdateFps(int fps)
  298. {
  299. updateFps_ = Max(fps, 1);
  300. updateInterval_ = 1.0f / (float)updateFps_;
  301. updateAcc_ = 0.0f;
  302. }
  303. void Network::SetSimulatedLatency(int ms)
  304. {
  305. simulatedLatency_ = Max(ms, 0);
  306. ConfigureNetworkSimulator();
  307. }
  308. void Network::SetSimulatedPacketLoss(float loss)
  309. {
  310. simulatedPacketLoss_ = Clamp(loss, 0.0f, 1.0f);
  311. ConfigureNetworkSimulator();
  312. }
  313. void Network::RegisterRemoteEvent(StringHash eventType)
  314. {
  315. if (blacklistedRemoteEvents_.Find(eventType) != blacklistedRemoteEvents_.End())
  316. {
  317. ATOMIC_LOGERROR("Attempted to register blacklisted remote event type " + String(eventType));
  318. return;
  319. }
  320. allowedRemoteEvents_.Insert(eventType);
  321. }
  322. void Network::UnregisterRemoteEvent(StringHash eventType)
  323. {
  324. allowedRemoteEvents_.Erase(eventType);
  325. }
  326. void Network::UnregisterAllRemoteEvents()
  327. {
  328. allowedRemoteEvents_.Clear();
  329. }
  330. void Network::SetPackageCacheDir(const String& path)
  331. {
  332. packageCacheDir_ = AddTrailingSlash(path);
  333. }
  334. void Network::SendPackageToClients(Scene* scene, PackageFile* package)
  335. {
  336. if (!scene)
  337. {
  338. ATOMIC_LOGERROR("Null scene specified for SendPackageToClients");
  339. return;
  340. }
  341. if (!package)
  342. {
  343. ATOMIC_LOGERROR("Null package specified for SendPackageToClients");
  344. return;
  345. }
  346. for (HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::Iterator i = clientConnections_.Begin();
  347. i != clientConnections_.End(); ++i)
  348. {
  349. if (i->second_->GetScene() == scene)
  350. i->second_->SendPackageToClient(package);
  351. }
  352. }
  353. SharedPtr<HttpRequest> Network::MakeHttpRequest(const String& url, const String& verb, const Vector<String>& headers,
  354. const String& postData)
  355. {
  356. ATOMIC_PROFILE(MakeHttpRequest);
  357. // The initialization of the request will take time, can not know at this point if it has an error or not
  358. SharedPtr<HttpRequest> request(new HttpRequest(url, verb, headers, postData));
  359. return request;
  360. }
  361. Connection* Network::GetConnection(kNet::MessageConnection* connection) const
  362. {
  363. if (serverConnection_ && serverConnection_->GetMessageConnection() == connection)
  364. return serverConnection_;
  365. else
  366. {
  367. HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Find(connection);
  368. if (i != clientConnections_.End())
  369. return i->second_;
  370. else
  371. return 0;
  372. }
  373. }
  374. Connection* Network::GetServerConnection() const
  375. {
  376. return serverConnection_;
  377. }
  378. Vector<SharedPtr<Connection> > Network::GetClientConnections() const
  379. {
  380. Vector<SharedPtr<Connection> > ret;
  381. for (HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Begin();
  382. i != clientConnections_.End(); ++i)
  383. ret.Push(i->second_);
  384. return ret;
  385. }
  386. bool Network::IsServerRunning() const
  387. {
  388. return network_->GetServer();
  389. }
  390. bool Network::CheckRemoteEvent(StringHash eventType) const
  391. {
  392. return allowedRemoteEvents_.Contains(eventType);
  393. }
  394. void Network::Update(float timeStep)
  395. {
  396. ATOMIC_PROFILE(UpdateNetwork);
  397. // Process server connection if it exists
  398. if (serverConnection_)
  399. {
  400. kNet::MessageConnection* connection = serverConnection_->GetMessageConnection();
  401. // Receive new messages
  402. connection->Process();
  403. // Process latest data messages waiting for the correct nodes or components to be created
  404. serverConnection_->ProcessPendingLatestData();
  405. // Check for state transitions
  406. kNet::ConnectionState state = connection->GetConnectionState();
  407. if (serverConnection_->IsConnectPending() && state == kNet::ConnectionOK)
  408. OnServerConnected();
  409. else if (state == kNet::ConnectionPeerClosed)
  410. serverConnection_->Disconnect();
  411. else if (state == kNet::ConnectionClosed)
  412. OnServerDisconnected();
  413. }
  414. // Process the network server if started
  415. kNet::SharedPtr<kNet::NetworkServer> server = network_->GetServer();
  416. if (server)
  417. server->Process();
  418. }
  419. void Network::PostUpdate(float timeStep)
  420. {
  421. ATOMIC_PROFILE(PostUpdateNetwork);
  422. // Check if periodic update should happen now
  423. updateAcc_ += timeStep;
  424. bool updateNow = updateAcc_ >= updateInterval_;
  425. if (updateNow)
  426. {
  427. // Notify of the impending update to allow for example updated client controls to be set
  428. SendEvent(E_NETWORKUPDATE);
  429. updateAcc_ = fmodf(updateAcc_, updateInterval_);
  430. if (IsServerRunning())
  431. {
  432. // Collect and prepare all networked scenes
  433. {
  434. ATOMIC_PROFILE(PrepareServerUpdate);
  435. networkScenes_.Clear();
  436. for (HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::Iterator i = clientConnections_.Begin();
  437. i != clientConnections_.End(); ++i)
  438. {
  439. Scene* scene = i->second_->GetScene();
  440. if (scene)
  441. networkScenes_.Insert(scene);
  442. }
  443. for (HashSet<Scene*>::ConstIterator i = networkScenes_.Begin(); i != networkScenes_.End(); ++i)
  444. (*i)->PrepareNetworkUpdate();
  445. }
  446. {
  447. ATOMIC_PROFILE(SendServerUpdate);
  448. // Then send server updates for each client connection
  449. for (HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::Iterator i = clientConnections_.Begin();
  450. i != clientConnections_.End(); ++i)
  451. {
  452. i->second_->SendServerUpdate();
  453. i->second_->SendRemoteEvents();
  454. i->second_->SendPackages();
  455. }
  456. }
  457. }
  458. if (serverConnection_)
  459. {
  460. // Send the client update
  461. serverConnection_->SendClientUpdate();
  462. serverConnection_->SendRemoteEvents();
  463. }
  464. // Notify that the update was sent
  465. SendEvent(E_NETWORKUPDATESENT);
  466. }
  467. }
  468. void Network::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  469. {
  470. using namespace BeginFrame;
  471. Update(eventData[P_TIMESTEP].GetFloat());
  472. }
  473. void Network::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  474. {
  475. using namespace RenderUpdate;
  476. PostUpdate(eventData[P_TIMESTEP].GetFloat());
  477. }
  478. void Network::OnServerConnected()
  479. {
  480. serverConnection_->SetConnectPending(false);
  481. ATOMIC_LOGINFO("Connected to server");
  482. // Send the identity map now
  483. VectorBuffer msg;
  484. msg.WriteVariantMap(serverConnection_->GetIdentity());
  485. serverConnection_->SendMessage(MSG_IDENTITY, true, true, msg);
  486. SendEvent(E_SERVERCONNECTED);
  487. }
  488. void Network::OnServerDisconnected()
  489. {
  490. // Differentiate between failed connection, and disconnection
  491. bool failedConnect = serverConnection_ && serverConnection_->IsConnectPending();
  492. serverConnection_.Reset();
  493. if (!failedConnect)
  494. {
  495. ATOMIC_LOGINFO("Disconnected from server");
  496. SendEvent(E_SERVERDISCONNECTED);
  497. }
  498. else
  499. {
  500. ATOMIC_LOGERROR("Failed to connect to server");
  501. SendEvent(E_CONNECTFAILED);
  502. }
  503. }
  504. void Network::ConfigureNetworkSimulator()
  505. {
  506. if (serverConnection_)
  507. serverConnection_->ConfigureNetworkSimulator(simulatedLatency_, simulatedPacketLoss_);
  508. for (HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::Iterator i = clientConnections_.Begin();
  509. i != clientConnections_.End(); ++i)
  510. i->second_->ConfigureNetworkSimulator(simulatedLatency_, simulatedPacketLoss_);
  511. }
  512. void RegisterNetworkLibrary(Context* context)
  513. {
  514. NetworkPriority::RegisterObject(context);
  515. }
  516. // ATOMIC BEGIN
  517. bool Network::ConnectWithExistingSocket(kNet::Socket* existingSocket, Scene* scene)
  518. {
  519. ATOMIC_PROFILE(ConnectWithExistingSocket);
  520. // If a previous connection already exists, disconnect it and wait for some time for the connection to terminate
  521. if (serverConnection_)
  522. {
  523. serverConnection_->Disconnect(100);
  524. OnServerDisconnected();
  525. }
  526. kNet::SharedPtr<kNet::MessageConnection> connection = network_->Connect(existingSocket, this);
  527. if (connection)
  528. {
  529. serverConnection_ = new Connection(context_, false, connection);
  530. serverConnection_->SetScene(scene);
  531. serverConnection_->SetIdentity(Variant::emptyVariantMap);
  532. serverConnection_->SetConnectPending(true);
  533. serverConnection_->ConfigureNetworkSimulator(simulatedLatency_, simulatedPacketLoss_);
  534. ATOMIC_LOGINFO("Connecting to server " + serverConnection_->ToString());
  535. return true;
  536. }
  537. else
  538. {
  539. ATOMIC_LOGERROR("Failed to connect to server ");
  540. SendEvent(E_CONNECTFAILED);
  541. return false;
  542. }
  543. }
  544. bool Network::IsEndPointConnected(const kNet::EndPoint& endPoint) const
  545. {
  546. Vector<SharedPtr<Connection> > ret;
  547. for (HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Begin();
  548. i != clientConnections_.End(); ++i)
  549. {
  550. kNet::EndPoint remoteEndPoint = i->first_->GetSocket()->RemoteEndPoint();
  551. if (endPoint.ToString()==remoteEndPoint.ToString())
  552. {
  553. return i->second_->IsConnected();
  554. }
  555. }
  556. return false;
  557. }
  558. // ATOMIC END
  559. }