Network.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. //
  2. // Copyright (c) 2008-2016 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. delete network_;
  112. network_ = 0;
  113. }
  114. void Network::HandleMessage(kNet::MessageConnection* source, kNet::packet_id_t packetId, kNet::message_id_t msgId, const char* data,
  115. size_t numBytes)
  116. {
  117. // Only process messages from known sources
  118. Connection* connection = GetConnection(source);
  119. if (connection)
  120. {
  121. MemoryBuffer msg(data, (unsigned)numBytes);
  122. if (connection->ProcessMessage((int)msgId, msg))
  123. return;
  124. // If message was not handled internally, forward as an event
  125. using namespace NetworkMessage;
  126. VariantMap& eventData = GetEventDataMap();
  127. eventData[P_CONNECTION] = connection;
  128. eventData[P_MESSAGEID] = (int)msgId;
  129. eventData[P_DATA].SetBuffer(msg.GetData(), msg.GetSize());
  130. connection->SendEvent(E_NETWORKMESSAGE, eventData);
  131. }
  132. else
  133. ATOMIC_LOGWARNING("Discarding message from unknown MessageConnection " + ToString((void*)source));
  134. }
  135. u32 Network::ComputeContentID(kNet::message_id_t msgId, const char* data, size_t numBytes)
  136. {
  137. switch (msgId)
  138. {
  139. case MSG_CONTROLS:
  140. // Return fixed content ID for controls
  141. return CONTROLS_CONTENT_ID;
  142. case MSG_NODELATESTDATA:
  143. case MSG_COMPONENTLATESTDATA:
  144. {
  145. // Return the node or component ID, which is first in the message
  146. MemoryBuffer msg(data, (unsigned)numBytes);
  147. return msg.ReadNetID();
  148. }
  149. default:
  150. // By default return no content ID
  151. return 0;
  152. }
  153. }
  154. void Network::NewConnectionEstablished(kNet::MessageConnection* connection)
  155. {
  156. connection->RegisterInboundMessageHandler(this);
  157. // Create a new client connection corresponding to this MessageConnection
  158. SharedPtr<Connection> newConnection(new Connection(context_, true, kNet::SharedPtr<kNet::MessageConnection>(connection)));
  159. newConnection->ConfigureNetworkSimulator(simulatedLatency_, simulatedPacketLoss_);
  160. clientConnections_[connection] = newConnection;
  161. ATOMIC_LOGINFO("Client " + newConnection->ToString() + " connected");
  162. using namespace ClientConnected;
  163. VariantMap& eventData = GetEventDataMap();
  164. eventData[P_CONNECTION] = newConnection;
  165. newConnection->SendEvent(E_CLIENTCONNECTED, eventData);
  166. }
  167. void Network::ClientDisconnected(kNet::MessageConnection* connection)
  168. {
  169. connection->Disconnect(0);
  170. // Remove the client connection that corresponds to this MessageConnection
  171. HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::Iterator i = clientConnections_.Find(connection);
  172. if (i != clientConnections_.End())
  173. {
  174. Connection* connection = i->second_;
  175. ATOMIC_LOGINFO("Client " + connection->ToString() + " disconnected");
  176. using namespace ClientDisconnected;
  177. VariantMap& eventData = GetEventDataMap();
  178. eventData[P_CONNECTION] = connection;
  179. connection->SendEvent(E_CLIENTDISCONNECTED, eventData);
  180. clientConnections_.Erase(i);
  181. }
  182. }
  183. bool Network::Connect(const String& address, unsigned short port, Scene* scene, const VariantMap& identity)
  184. {
  185. ATOMIC_PROFILE(Connect);
  186. // If a previous connection already exists, disconnect it and wait for some time for the connection to terminate
  187. if (serverConnection_)
  188. {
  189. serverConnection_->Disconnect(100);
  190. OnServerDisconnected();
  191. }
  192. kNet::SharedPtr<kNet::MessageConnection> connection = network_->Connect(address.CString(), port, kNet::SocketOverUDP, this);
  193. if (connection)
  194. {
  195. serverConnection_ = new Connection(context_, false, connection);
  196. serverConnection_->SetScene(scene);
  197. serverConnection_->SetIdentity(identity);
  198. serverConnection_->SetConnectPending(true);
  199. serverConnection_->ConfigureNetworkSimulator(simulatedLatency_, simulatedPacketLoss_);
  200. ATOMIC_LOGINFO("Connecting to server " + serverConnection_->ToString());
  201. return true;
  202. }
  203. else
  204. {
  205. ATOMIC_LOGERROR("Failed to connect to server " + address + ":" + String(port));
  206. SendEvent(E_CONNECTFAILED);
  207. return false;
  208. }
  209. }
  210. void Network::Disconnect(int waitMSec)
  211. {
  212. if (!serverConnection_)
  213. return;
  214. ATOMIC_PROFILE(Disconnect);
  215. serverConnection_->Disconnect(waitMSec);
  216. }
  217. bool Network::StartServer(unsigned short port)
  218. {
  219. if (IsServerRunning())
  220. return true;
  221. ATOMIC_PROFILE(StartServer);
  222. // ATOMIC BEGIN
  223. serverPort_ = port;
  224. // ATOMIC END
  225. if (network_->StartServer(port, kNet::SocketOverUDP, this, true) != 0)
  226. {
  227. ATOMIC_LOGINFO("Started server on port " + String(port));
  228. return true;
  229. }
  230. else
  231. {
  232. ATOMIC_LOGERROR("Failed to start server on port " + String(port));
  233. return false;
  234. }
  235. }
  236. void Network::StopServer()
  237. {
  238. if (!IsServerRunning())
  239. return;
  240. ATOMIC_PROFILE(StopServer);
  241. clientConnections_.Clear();
  242. network_->StopServer();
  243. ATOMIC_LOGINFO("Stopped server");
  244. }
  245. void Network::BroadcastMessage(int msgID, bool reliable, bool inOrder, const VectorBuffer& msg, unsigned contentID)
  246. {
  247. BroadcastMessage(msgID, reliable, inOrder, msg.GetData(), msg.GetSize(), contentID);
  248. }
  249. void Network::BroadcastMessage(int msgID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes,
  250. unsigned contentID)
  251. {
  252. // Make sure not to use kNet internal message ID's
  253. if (msgID <= 0x4 || msgID >= 0x3ffffffe)
  254. {
  255. ATOMIC_LOGERROR("Can not send message with reserved ID");
  256. return;
  257. }
  258. kNet::NetworkServer* server = network_->GetServer();
  259. if (server)
  260. server->BroadcastMessage((unsigned long)msgID, reliable, inOrder, 0, contentID, (const char*)data, numBytes);
  261. else
  262. ATOMIC_LOGERROR("Server not running, can not broadcast messages");
  263. }
  264. void Network::BroadcastRemoteEvent(StringHash eventType, bool inOrder, const VariantMap& eventData)
  265. {
  266. for (HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::Iterator i = clientConnections_.Begin();
  267. i != clientConnections_.End(); ++i)
  268. i->second_->SendRemoteEvent(eventType, inOrder, eventData);
  269. }
  270. void Network::BroadcastRemoteEvent(Scene* scene, StringHash eventType, bool inOrder, const VariantMap& eventData)
  271. {
  272. for (HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::Iterator i = clientConnections_.Begin();
  273. i != clientConnections_.End(); ++i)
  274. {
  275. if (i->second_->GetScene() == scene)
  276. i->second_->SendRemoteEvent(eventType, inOrder, eventData);
  277. }
  278. }
  279. void Network::BroadcastRemoteEvent(Node* node, StringHash eventType, bool inOrder, const VariantMap& eventData)
  280. {
  281. if (!node)
  282. {
  283. ATOMIC_LOGERROR("Null sender node for remote node event");
  284. return;
  285. }
  286. if (node->GetID() >= FIRST_LOCAL_ID)
  287. {
  288. ATOMIC_LOGERROR("Sender node has a local ID, can not send remote node event");
  289. return;
  290. }
  291. Scene* scene = node->GetScene();
  292. for (HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::Iterator i = clientConnections_.Begin();
  293. i != clientConnections_.End(); ++i)
  294. {
  295. if (i->second_->GetScene() == scene)
  296. i->second_->SendRemoteEvent(node, eventType, inOrder, eventData);
  297. }
  298. }
  299. void Network::SetUpdateFps(int fps)
  300. {
  301. updateFps_ = Max(fps, 1);
  302. updateInterval_ = 1.0f / (float)updateFps_;
  303. updateAcc_ = 0.0f;
  304. }
  305. void Network::SetSimulatedLatency(int ms)
  306. {
  307. simulatedLatency_ = Max(ms, 0);
  308. ConfigureNetworkSimulator();
  309. }
  310. void Network::SetSimulatedPacketLoss(float loss)
  311. {
  312. simulatedPacketLoss_ = Clamp(loss, 0.0f, 1.0f);
  313. ConfigureNetworkSimulator();
  314. }
  315. void Network::RegisterRemoteEvent(StringHash eventType)
  316. {
  317. if (blacklistedRemoteEvents_.Find(eventType) != blacklistedRemoteEvents_.End())
  318. {
  319. ATOMIC_LOGERROR("Attempted to register blacklisted remote event type " + String(eventType));
  320. return;
  321. }
  322. allowedRemoteEvents_.Insert(eventType);
  323. }
  324. void Network::UnregisterRemoteEvent(StringHash eventType)
  325. {
  326. allowedRemoteEvents_.Erase(eventType);
  327. }
  328. void Network::UnregisterAllRemoteEvents()
  329. {
  330. allowedRemoteEvents_.Clear();
  331. }
  332. void Network::SetPackageCacheDir(const String& path)
  333. {
  334. packageCacheDir_ = AddTrailingSlash(path);
  335. }
  336. void Network::SendPackageToClients(Scene* scene, PackageFile* package)
  337. {
  338. if (!scene)
  339. {
  340. ATOMIC_LOGERROR("Null scene specified for SendPackageToClients");
  341. return;
  342. }
  343. if (!package)
  344. {
  345. ATOMIC_LOGERROR("Null package specified for SendPackageToClients");
  346. return;
  347. }
  348. for (HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::Iterator i = clientConnections_.Begin();
  349. i != clientConnections_.End(); ++i)
  350. {
  351. if (i->second_->GetScene() == scene)
  352. i->second_->SendPackageToClient(package);
  353. }
  354. }
  355. SharedPtr<HttpRequest> Network::MakeHttpRequest(const String& url, const String& verb, const Vector<String>& headers,
  356. const String& postData)
  357. {
  358. ATOMIC_PROFILE(MakeHttpRequest);
  359. // The initialization of the request will take time, can not know at this point if it has an error or not
  360. SharedPtr<HttpRequest> request(new HttpRequest(url, verb, headers, postData));
  361. return request;
  362. }
  363. Connection* Network::GetConnection(kNet::MessageConnection* connection) const
  364. {
  365. if (serverConnection_ && serverConnection_->GetMessageConnection() == connection)
  366. return serverConnection_;
  367. else
  368. {
  369. HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Find(connection);
  370. if (i != clientConnections_.End())
  371. return i->second_;
  372. else
  373. return 0;
  374. }
  375. }
  376. Connection* Network::GetServerConnection() const
  377. {
  378. return serverConnection_;
  379. }
  380. Vector<SharedPtr<Connection> > Network::GetClientConnections() const
  381. {
  382. Vector<SharedPtr<Connection> > ret;
  383. for (HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Begin();
  384. i != clientConnections_.End(); ++i)
  385. ret.Push(i->second_);
  386. return ret;
  387. }
  388. bool Network::IsServerRunning() const
  389. {
  390. return network_->GetServer();
  391. }
  392. bool Network::CheckRemoteEvent(StringHash eventType) const
  393. {
  394. return allowedRemoteEvents_.Contains(eventType);
  395. }
  396. void Network::Update(float timeStep)
  397. {
  398. ATOMIC_PROFILE(UpdateNetwork);
  399. // Process server connection if it exists
  400. if (serverConnection_)
  401. {
  402. kNet::MessageConnection* connection = serverConnection_->GetMessageConnection();
  403. // Receive new messages
  404. connection->Process();
  405. // Process latest data messages waiting for the correct nodes or components to be created
  406. serverConnection_->ProcessPendingLatestData();
  407. // Check for state transitions
  408. kNet::ConnectionState state = connection->GetConnectionState();
  409. if (serverConnection_->IsConnectPending() && state == kNet::ConnectionOK)
  410. OnServerConnected();
  411. else if (state == kNet::ConnectionPeerClosed)
  412. serverConnection_->Disconnect();
  413. else if (state == kNet::ConnectionClosed)
  414. OnServerDisconnected();
  415. }
  416. // Process the network server if started
  417. kNet::SharedPtr<kNet::NetworkServer> server = network_->GetServer();
  418. if (server)
  419. server->Process();
  420. }
  421. void Network::PostUpdate(float timeStep)
  422. {
  423. ATOMIC_PROFILE(PostUpdateNetwork);
  424. // Check if periodic update should happen now
  425. updateAcc_ += timeStep;
  426. bool updateNow = updateAcc_ >= updateInterval_;
  427. if (updateNow)
  428. {
  429. // Notify of the impending update to allow for example updated client controls to be set
  430. SendEvent(E_NETWORKUPDATE);
  431. updateAcc_ = fmodf(updateAcc_, updateInterval_);
  432. if (IsServerRunning())
  433. {
  434. // Collect and prepare all networked scenes
  435. {
  436. ATOMIC_PROFILE(PrepareServerUpdate);
  437. networkScenes_.Clear();
  438. for (HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::Iterator i = clientConnections_.Begin();
  439. i != clientConnections_.End(); ++i)
  440. {
  441. Scene* scene = i->second_->GetScene();
  442. if (scene)
  443. networkScenes_.Insert(scene);
  444. }
  445. for (HashSet<Scene*>::ConstIterator i = networkScenes_.Begin(); i != networkScenes_.End(); ++i)
  446. (*i)->PrepareNetworkUpdate();
  447. }
  448. {
  449. ATOMIC_PROFILE(SendServerUpdate);
  450. // Then send server updates for each client connection
  451. for (HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::Iterator i = clientConnections_.Begin();
  452. i != clientConnections_.End(); ++i)
  453. {
  454. i->second_->SendServerUpdate();
  455. i->second_->SendRemoteEvents();
  456. i->second_->SendPackages();
  457. }
  458. }
  459. }
  460. if (serverConnection_)
  461. {
  462. // Send the client update
  463. serverConnection_->SendClientUpdate();
  464. serverConnection_->SendRemoteEvents();
  465. }
  466. // Notify that the update was sent
  467. SendEvent(E_NETWORKUPDATESENT);
  468. }
  469. }
  470. void Network::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  471. {
  472. using namespace BeginFrame;
  473. Update(eventData[P_TIMESTEP].GetFloat());
  474. }
  475. void Network::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  476. {
  477. using namespace RenderUpdate;
  478. PostUpdate(eventData[P_TIMESTEP].GetFloat());
  479. }
  480. void Network::OnServerConnected()
  481. {
  482. serverConnection_->SetConnectPending(false);
  483. ATOMIC_LOGINFO("Connected to server");
  484. // Send the identity map now
  485. VectorBuffer msg;
  486. msg.WriteVariantMap(serverConnection_->GetIdentity());
  487. serverConnection_->SendMessage(MSG_IDENTITY, true, true, msg);
  488. SendEvent(E_SERVERCONNECTED);
  489. }
  490. void Network::OnServerDisconnected()
  491. {
  492. // Differentiate between failed connection, and disconnection
  493. bool failedConnect = serverConnection_ && serverConnection_->IsConnectPending();
  494. serverConnection_.Reset();
  495. if (!failedConnect)
  496. {
  497. ATOMIC_LOGINFO("Disconnected from server");
  498. SendEvent(E_SERVERDISCONNECTED);
  499. }
  500. else
  501. {
  502. ATOMIC_LOGERROR("Failed to connect to server");
  503. SendEvent(E_CONNECTFAILED);
  504. }
  505. }
  506. void Network::ConfigureNetworkSimulator()
  507. {
  508. if (serverConnection_)
  509. serverConnection_->ConfigureNetworkSimulator(simulatedLatency_, simulatedPacketLoss_);
  510. for (HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::Iterator i = clientConnections_.Begin();
  511. i != clientConnections_.End(); ++i)
  512. i->second_->ConfigureNetworkSimulator(simulatedLatency_, simulatedPacketLoss_);
  513. }
  514. void RegisterNetworkLibrary(Context* context)
  515. {
  516. NetworkPriority::RegisterObject(context);
  517. }
  518. // ATOMIC BEGIN
  519. bool Network::ConnectWithExistingSocket(kNet::Socket* existingSocket, Scene* scene)
  520. {
  521. ATOMIC_PROFILE(ConnectWithExistingSocket);
  522. // If a previous connection already exists, disconnect it and wait for some time for the connection to terminate
  523. if (serverConnection_)
  524. {
  525. serverConnection_->Disconnect(100);
  526. OnServerDisconnected();
  527. }
  528. kNet::SharedPtr<kNet::MessageConnection> connection = network_->Connect(existingSocket, this);
  529. if (connection)
  530. {
  531. serverConnection_ = new Connection(context_, false, connection);
  532. serverConnection_->SetScene(scene);
  533. serverConnection_->SetIdentity(Variant::emptyVariantMap);
  534. serverConnection_->SetConnectPending(true);
  535. serverConnection_->ConfigureNetworkSimulator(simulatedLatency_, simulatedPacketLoss_);
  536. ATOMIC_LOGINFO("Connecting to server " + serverConnection_->ToString());
  537. return true;
  538. }
  539. else
  540. {
  541. ATOMIC_LOGERROR("Failed to connect to server ");
  542. SendEvent(E_CONNECTFAILED);
  543. return false;
  544. }
  545. }
  546. bool Network::IsEndPointConnected(const kNet::EndPoint& endPoint) const
  547. {
  548. Vector<SharedPtr<Connection> > ret;
  549. for (HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Begin();
  550. i != clientConnections_.End(); ++i)
  551. {
  552. kNet::EndPoint remoteEndPoint = i->first_->GetSocket()->RemoteEndPoint();
  553. if (endPoint.ToString()==remoteEndPoint.ToString())
  554. {
  555. return i->second_->IsConnected();
  556. }
  557. }
  558. return false;
  559. }
  560. // ATOMIC END
  561. }