Network.cpp 22 KB

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