Network.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Context.h"
  25. #include "CoreEvents.h"
  26. #include "FileSystem.h"
  27. #include "Log.h"
  28. #include "MemoryBuffer.h"
  29. #include "Network.h"
  30. #include "NetworkEvents.h"
  31. #include "NetworkPriority.h"
  32. #include "Profiler.h"
  33. #include "Protocol.h"
  34. #include "Scene.h"
  35. #include "StringUtils.h"
  36. #include <kNet.h>
  37. #include "DebugNew.h"
  38. static const int DEFAULT_UPDATE_FPS = 30;
  39. OBJECTTYPESTATIC(Network);
  40. Network::Network(Context* context) :
  41. Object(context),
  42. updateFps_(DEFAULT_UPDATE_FPS),
  43. updateInterval_(1.0f / (float)DEFAULT_UPDATE_FPS),
  44. updateAcc_(0.0f)
  45. {
  46. network_ = new kNet::Network();
  47. SubscribeToEvent(E_BEGINFRAME, HANDLER(Network, HandleBeginFrame));
  48. SubscribeToEvent(E_RENDERUPDATE, HANDLER(Network, HandleRenderUpdate));
  49. }
  50. Network::~Network()
  51. {
  52. // If server connection exists, disconnect, but do not send an event because we are shutting down
  53. Disconnect(100);
  54. serverConnection_.Reset();
  55. clientConnections_.Clear();
  56. delete network_;
  57. network_ = 0;
  58. }
  59. void Network::HandleMessage(kNet::MessageConnection* source, kNet::message_id_t id, const char* data, size_t numBytes)
  60. {
  61. // Only process messages from known sources
  62. Connection* connection = GetConnection(source);
  63. if (connection)
  64. {
  65. MemoryBuffer msg(data, numBytes);
  66. switch (id)
  67. {
  68. case MSG_IDENTITY:
  69. connection->ProcessIdentity(id, msg);
  70. return;
  71. case MSG_CONTROLS:
  72. connection->ProcessControls(id, msg);
  73. return;
  74. case MSG_SCENELOADED:
  75. connection->ProcessSceneLoaded(id, msg);
  76. return;
  77. case MSG_REQUESTPACKAGE:
  78. case MSG_PACKAGEDATA:
  79. connection->ProcessPackageDownload(id, msg);
  80. return;
  81. case MSG_LOADSCENE:
  82. connection->ProcessLoadScene(id, msg);
  83. return;
  84. case MSG_SCENECHECKSUMERROR:
  85. connection->ProcessSceneChecksumError(id, msg);
  86. return;
  87. case MSG_CREATENODE:
  88. case MSG_NODEDELTAUPDATE:
  89. case MSG_NODELATESTDATA:
  90. case MSG_REMOVENODE:
  91. case MSG_CREATECOMPONENT:
  92. case MSG_COMPONENTDELTAUPDATE:
  93. case MSG_COMPONENTLATESTDATA:
  94. case MSG_REMOVECOMPONENT:
  95. connection->ProcessSceneUpdate(id, msg);
  96. return;
  97. case MSG_REMOTEEVENT:
  98. case MSG_REMOTENODEEVENT:
  99. connection->ProcessRemoteEvent(id, msg);
  100. return;
  101. }
  102. // If message was not handled internally, forward as an event
  103. using namespace NetworkMessage;
  104. VariantMap eventData;
  105. eventData[P_CONNECTION] = (void*)connection;
  106. eventData[P_MESSAGEID] = (int)id;
  107. eventData[P_DATA].SetBuffer(msg.GetData(), msg.GetSize());
  108. connection->SendEvent(E_NETWORKMESSAGE, eventData);
  109. }
  110. else
  111. LOGWARNING("Discarding message from unknown MessageConnection " + ToString((void*)source));
  112. }
  113. u32 Network::ComputeContentID(kNet::message_id_t id, const char* data, size_t numBytes)
  114. {
  115. switch (id)
  116. {
  117. case MSG_CONTROLS:
  118. // Return fixed content ID for controls
  119. return CONTROLS_CONTENT_ID;
  120. case MSG_NODELATESTDATA:
  121. case MSG_COMPONENTLATESTDATA:
  122. {
  123. // Return the node or component ID, which is first in the message
  124. MemoryBuffer msg(data, numBytes);
  125. return msg.ReadNetID();
  126. }
  127. default:
  128. // By default return no content ID
  129. return 0;
  130. }
  131. }
  132. void Network::NewConnectionEstablished(kNet::MessageConnection* connection)
  133. {
  134. connection->RegisterInboundMessageHandler(this);
  135. // Create a new client connection corresponding to this MessageConnection
  136. Connection* newConnection = new Connection(context_, true, kNet::SharedPtr<kNet::MessageConnection>(connection));
  137. clientConnections_[connection] = newConnection;
  138. LOGINFO("Client " + newConnection->ToString() + " connected");
  139. using namespace ClientConnected;
  140. VariantMap eventData;
  141. eventData[P_CONNECTION] = (void*)newConnection;
  142. newConnection->SendEvent(E_CLIENTCONNECTED, eventData);
  143. }
  144. void Network::ClientDisconnected(kNet::MessageConnection* connection)
  145. {
  146. connection->Disconnect(0);
  147. // Remove the client connection that corresponds to this MessageConnection
  148. Map<kNet::MessageConnection*, SharedPtr<Connection> >::Iterator i = clientConnections_.Find(connection);
  149. if (i != clientConnections_.End())
  150. {
  151. Connection* connection = i->second_;
  152. LOGINFO("Client " + connection->ToString() + " disconnected");
  153. using namespace ClientDisconnected;
  154. VariantMap eventData;
  155. eventData[P_CONNECTION] = (void*)connection;
  156. connection->SendEvent(E_CLIENTDISCONNECTED, eventData);
  157. clientConnections_.Erase(i);
  158. }
  159. }
  160. bool Network::Connect(const String& address, unsigned short port, Scene* scene, const VariantMap& identity)
  161. {
  162. PROFILE(Connect);
  163. // If a previous connection already exists, disconnect it and wait for some time for the connection to terminate
  164. if (serverConnection_)
  165. {
  166. serverConnection_->Disconnect(100);
  167. OnServerDisconnected();
  168. }
  169. kNet::SharedPtr<kNet::MessageConnection> connection = network_->Connect(address.CString(), port, kNet::SocketOverUDP, this);
  170. if (connection)
  171. {
  172. LOGINFO("Connecting to server " + address + ":" + String(port));
  173. serverConnection_ = new Connection(context_, false, connection);
  174. serverConnection_->SetScene(scene);
  175. serverConnection_->SetIdentity(identity);
  176. serverConnection_->SetConnectPending(true);
  177. return true;
  178. }
  179. else
  180. {
  181. LOGERROR("Failed to connect to server " + address + ":" + String(port));
  182. SendEvent(E_CONNECTFAILED);
  183. return false;
  184. }
  185. }
  186. void Network::Disconnect(int waitMSec)
  187. {
  188. if (!serverConnection_)
  189. return;
  190. PROFILE(Disconnect);
  191. serverConnection_->Disconnect(waitMSec);
  192. }
  193. bool Network::StartServer(unsigned short port)
  194. {
  195. if (IsServerRunning())
  196. return true;
  197. PROFILE(StartServer);
  198. /// \todo Investigate why server fails to restart after stopping when false is specified for reuse
  199. if (network_->StartServer(port, kNet::SocketOverUDP, this, true) != 0)
  200. {
  201. LOGINFO("Started server on port " + String(port));
  202. return true;
  203. }
  204. else
  205. {
  206. LOGERROR("Failed to start server on port " + String(port));
  207. return false;
  208. }
  209. }
  210. void Network::StopServer()
  211. {
  212. if (!IsServerRunning())
  213. return;
  214. PROFILE(StopServer);
  215. clientConnections_.Clear();
  216. network_->StopServer();
  217. LOGINFO("Stopped server");
  218. }
  219. void Network::BroadcastMessage(int msgID, bool reliable, bool inOrder, const VectorBuffer& msg, unsigned priority,
  220. unsigned contentID)
  221. {
  222. BroadcastMessage(msgID, reliable, inOrder, msg.GetData(), msg.GetSize(), priority, contentID);
  223. }
  224. void Network::BroadcastMessage(int msgID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes,
  225. unsigned priority, unsigned contentID)
  226. {
  227. // Make sure not to use kNet internal message ID's
  228. if (msgID <= 0x4 || msgID >= 0x3ffffffe)
  229. {
  230. LOGERROR("Can not send message with reserved ID");
  231. return;
  232. }
  233. kNet::NetworkServer* server = network_->GetServer();
  234. if (server)
  235. server->BroadcastMessage(msgID, reliable, inOrder, priority, contentID, (const char*)data, numBytes);
  236. else
  237. LOGERROR("Server not running, can not broadcast messages");
  238. }
  239. void Network::BroadcastRemoteEvent(StringHash eventType, bool inOrder, const VariantMap& eventData)
  240. {
  241. for (Map<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Begin();
  242. i != clientConnections_.End(); ++i)
  243. i->second_->SendRemoteEvent(eventType, inOrder, eventData);
  244. }
  245. void Network::BroadcastRemoteEvent(Scene* scene, StringHash eventType, bool inOrder, const VariantMap& eventData)
  246. {
  247. for (Map<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Begin();
  248. i != clientConnections_.End(); ++i)
  249. {
  250. if (i->second_->GetScene() == scene)
  251. i->second_->SendRemoteEvent(eventType, inOrder, eventData);
  252. }
  253. }
  254. void Network::BroadcastRemoteEvent(Node* receiver, StringHash eventType, bool inOrder, const VariantMap& eventData)
  255. {
  256. if (!receiver)
  257. {
  258. LOGERROR("Null node for remote node event");
  259. return;
  260. }
  261. if (receiver->GetID() >= FIRST_LOCAL_ID)
  262. {
  263. LOGERROR("Node has a local ID, can not send remote node event");
  264. return;
  265. }
  266. Scene* scene = receiver->GetScene();
  267. for (Map<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Begin();
  268. i != clientConnections_.End(); ++i)
  269. {
  270. if (i->second_->GetScene() == scene)
  271. i->second_->SendRemoteEvent(receiver, eventType, inOrder, eventData);
  272. }
  273. }
  274. void Network::SetUpdateFps(int fps)
  275. {
  276. updateFps_ = Max(fps, 1);
  277. updateInterval_ = 1.0f / (float)updateFps_;
  278. updateAcc_ = 0.0f;
  279. }
  280. void Network::RegisterRemoteEvent(StringHash eventType)
  281. {
  282. allowedRemoteEvents_.Insert(eventType);
  283. }
  284. void Network::UnregisterRemoteEvent(StringHash eventType)
  285. {
  286. allowedRemoteEvents_.Erase(eventType);
  287. }
  288. void Network::UnregisterAllRemoteEvents()
  289. {
  290. allowedRemoteEvents_.Clear();
  291. }
  292. void Network::SetPackageCacheDir(const String& path)
  293. {
  294. packageCacheDir_ = AddTrailingSlash(path);
  295. }
  296. Connection* Network::GetConnection(kNet::MessageConnection* connection) const
  297. {
  298. Map<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Find(connection);
  299. if (i != clientConnections_.End())
  300. return i->second_;
  301. else if (serverConnection_ && serverConnection_->GetMessageConnection() == connection)
  302. return serverConnection_;
  303. else
  304. return 0;
  305. }
  306. Connection* Network::GetServerConnection() const
  307. {
  308. return serverConnection_;
  309. }
  310. bool Network::IsServerRunning() const
  311. {
  312. return network_->GetServer();
  313. }
  314. bool Network::CheckRemoteEvent(StringHash eventType) const
  315. {
  316. return allowedRemoteEvents_.Empty() || allowedRemoteEvents_.Contains(eventType);
  317. }
  318. void Network::Update(float timeStep)
  319. {
  320. PROFILE(UpdateNetwork);
  321. // Process server connection if it exists
  322. if (serverConnection_)
  323. {
  324. kNet::MessageConnection* connection = serverConnection_->GetMessageConnection();
  325. // Receive new messages
  326. connection->Process();
  327. // Process latest data messages waiting for the correct nodes or components to be created
  328. serverConnection_->ProcessPendingLatestData();
  329. // Check for state transitions
  330. kNet::ConnectionState state = connection->GetConnectionState();
  331. if (serverConnection_->IsConnectPending() && state == kNet::ConnectionOK)
  332. OnServerConnected();
  333. else if (state == kNet::ConnectionPeerClosed)
  334. serverConnection_->Disconnect();
  335. else if (state == kNet::ConnectionClosed)
  336. OnServerDisconnected();
  337. }
  338. // Process the network server if started
  339. kNet::SharedPtr<kNet::NetworkServer> server = network_->GetServer();
  340. if (server)
  341. server->Process();
  342. }
  343. void Network::PostUpdate(float timeStep)
  344. {
  345. PROFILE(PostUpdateNetwork);
  346. // Check if periodic update should happen now
  347. updateAcc_ += timeStep;
  348. bool updateNow = updateAcc_ >= updateInterval_;
  349. if (updateNow)
  350. {
  351. // Notify of the impending update to allow for example updated client controls to be set
  352. SendEvent(E_NETWORKUPDATE);
  353. updateAcc_ = fmodf(updateAcc_, updateInterval_);
  354. if (IsServerRunning())
  355. {
  356. // Collect and update all networked scenes
  357. networkScenes_.Clear();
  358. for (Map<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Begin();
  359. i != clientConnections_.End(); ++i)
  360. {
  361. Scene* scene = i->second_->GetScene();
  362. if (scene)
  363. networkScenes_.Insert(scene);
  364. }
  365. for (HashSet<Scene*>::ConstIterator i = networkScenes_.Begin(); i != networkScenes_.End(); ++i)
  366. {
  367. PROFILE(PrepareServerUpdate);
  368. (*i)->PrepareNetworkUpdate();
  369. }
  370. // Send server updates for each client connection
  371. for (Map<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Begin();
  372. i != clientConnections_.End(); ++i)
  373. {
  374. i->second_->SendServerUpdate();
  375. i->second_->SendRemoteEvents();
  376. i->second_->SendPackages();
  377. }
  378. }
  379. if (serverConnection_)
  380. {
  381. // Send the client update
  382. serverConnection_->SendClientUpdate();
  383. serverConnection_->SendRemoteEvents();
  384. }
  385. // Notify that the update was sent
  386. SendEvent(E_NETWORKUPDATESENT);
  387. }
  388. }
  389. void Network::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  390. {
  391. using namespace BeginFrame;
  392. Update(eventData[P_TIMESTEP].GetFloat());
  393. }
  394. void Network::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  395. {
  396. using namespace RenderUpdate;
  397. PostUpdate(eventData[P_TIMESTEP].GetFloat());
  398. }
  399. void Network::OnServerConnected()
  400. {
  401. serverConnection_->SetConnectPending(false);
  402. LOGINFO("Connected to server");
  403. // Send the identity map now
  404. VectorBuffer msg;
  405. msg.WriteVariantMap(serverConnection_->GetIdentity());
  406. serverConnection_->SendMessage(MSG_IDENTITY, true, true, msg, NET_HIGH_PRIORITY);
  407. SendEvent(E_SERVERCONNECTED);
  408. }
  409. void Network::OnServerDisconnected()
  410. {
  411. // Differentiate between failed connection, and disconnection
  412. bool failedConnect = serverConnection_ && serverConnection_->IsConnectPending();
  413. if (!failedConnect)
  414. {
  415. LOGINFO("Disconnected from server");
  416. SendEvent(E_SERVERDISCONNECTED);
  417. }
  418. else
  419. {
  420. LOGERROR("Failed to connect to server");
  421. SendEvent(E_CONNECTFAILED);
  422. }
  423. serverConnection_.Reset();
  424. }
  425. void RegisterNetworkLibrary(Context* context)
  426. {
  427. NetworkPriority::RegisterObject(context);
  428. }