Network.cpp 19 KB

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