Network.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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. frameNumber_(1)
  46. {
  47. network_ = new kNet::Network();
  48. SubscribeToEvent(E_BEGINFRAME, HANDLER(Network, HandleBeginFrame));
  49. SubscribeToEvent(E_RENDERUPDATE, HANDLER(Network, HandleRenderUpdate));
  50. }
  51. Network::~Network()
  52. {
  53. // If server connection exists, disconnect, but do not send an event because we are shutting down
  54. Disconnect(100);
  55. serverConnection_.Reset();
  56. clientConnections_.Clear();
  57. delete network_;
  58. network_ = 0;
  59. }
  60. void Network::HandleMessage(kNet::MessageConnection* source, kNet::message_id_t id, const char* data, size_t numBytes)
  61. {
  62. // Only process messages from known sources
  63. Connection* connection = GetConnection(source);
  64. if (connection)
  65. {
  66. MemoryBuffer msg(data, numBytes);
  67. switch (id)
  68. {
  69. case MSG_IDENTITY:
  70. connection->ProcessIdentity(id, msg);
  71. return;
  72. case MSG_CONTROLS:
  73. connection->ProcessControls(id, msg);
  74. return;
  75. case MSG_SCENELOADED:
  76. connection->ProcessSceneLoaded(id, msg);
  77. return;
  78. case MSG_REQUESTPACKAGE:
  79. case MSG_PACKAGEDATA:
  80. connection->ProcessPackageDownload(id, msg);
  81. return;
  82. case MSG_LOADSCENE:
  83. connection->ProcessLoadScene(id, msg);
  84. return;
  85. case MSG_SCENECHECKSUMERROR:
  86. connection->ProcessSceneChecksumError(id, msg);
  87. return;
  88. case MSG_CREATENODE:
  89. case MSG_NODEDELTAUPDATE:
  90. case MSG_NODELATESTDATA:
  91. case MSG_REMOVENODE:
  92. case MSG_CREATECOMPONENT:
  93. case MSG_COMPONENTDELTAUPDATE:
  94. case MSG_COMPONENTLATESTDATA:
  95. case MSG_REMOVECOMPONENT:
  96. connection->ProcessSceneUpdate(id, msg);
  97. return;
  98. case MSG_REMOTEEVENT:
  99. case MSG_REMOTENODEEVENT:
  100. connection->ProcessRemoteEvent(id, msg);
  101. return;
  102. }
  103. // If message was not handled internally, forward as an event
  104. using namespace NetworkMessage;
  105. VariantMap eventData;
  106. eventData[P_CONNECTION] = (void*)connection;
  107. eventData[P_MESSAGEID] = (int)id;
  108. eventData[P_DATA].SetBuffer(msg.GetData(), msg.GetSize());
  109. connection->SendEvent(E_NETWORKMESSAGE, eventData);
  110. }
  111. else
  112. LOGWARNING("Discarding message from unknown MessageConnection " + ToString((void*)source));
  113. }
  114. u32 Network::ComputeContentID(kNet::message_id_t id, const char* data, size_t numBytes)
  115. {
  116. switch (id)
  117. {
  118. case MSG_CONTROLS:
  119. // Return fixed content ID for controls
  120. return CONTROLS_CONTENT_ID;
  121. case MSG_NODELATESTDATA:
  122. case MSG_COMPONENTLATESTDATA:
  123. {
  124. // Return the node or component ID, which is first in the message
  125. MemoryBuffer msg(data, numBytes);
  126. return msg.ReadNetID();
  127. }
  128. default:
  129. // By default return no content ID
  130. return 0;
  131. }
  132. }
  133. void Network::NewConnectionEstablished(kNet::MessageConnection* connection)
  134. {
  135. connection->RegisterInboundMessageHandler(this);
  136. // Create a new client connection corresponding to this MessageConnection
  137. Connection* newConnection = new Connection(context_, true, kNet::SharedPtr<kNet::MessageConnection>(connection));
  138. clientConnections_[connection] = newConnection;
  139. LOGINFO("Client " + newConnection->ToString() + " connected");
  140. using namespace ClientConnected;
  141. VariantMap eventData;
  142. eventData[P_CONNECTION] = (void*)newConnection;
  143. newConnection->SendEvent(E_CLIENTCONNECTED, eventData);
  144. }
  145. void Network::ClientDisconnected(kNet::MessageConnection* connection)
  146. {
  147. connection->Disconnect(0);
  148. // Remove the client connection that corresponds to this MessageConnection
  149. HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::Iterator i = clientConnections_.Find(connection);
  150. if (i != clientConnections_.End())
  151. {
  152. Connection* connection = i->second_;
  153. LOGINFO("Client " + connection->ToString() + " disconnected");
  154. using namespace ClientDisconnected;
  155. VariantMap eventData;
  156. eventData[P_CONNECTION] = (void*)connection;
  157. connection->SendEvent(E_CLIENTDISCONNECTED, eventData);
  158. clientConnections_.Erase(i);
  159. }
  160. }
  161. bool Network::Connect(const String& address, unsigned short port, Scene* scene, const VariantMap& identity)
  162. {
  163. PROFILE(Connect);
  164. // If a previous connection already exists, disconnect it and wait for some time for the connection to terminate
  165. if (serverConnection_)
  166. {
  167. serverConnection_->Disconnect(100);
  168. OnServerDisconnected();
  169. }
  170. kNet::SharedPtr<kNet::MessageConnection> connection = network_->Connect(address.CString(), port, kNet::SocketOverUDP, this);
  171. if (connection)
  172. {
  173. LOGINFO("Connecting to server " + address + ":" + String(port));
  174. serverConnection_ = new Connection(context_, false, connection);
  175. serverConnection_->SetScene(scene);
  176. serverConnection_->SetIdentity(identity);
  177. serverConnection_->SetConnectPending(true);
  178. return true;
  179. }
  180. else
  181. {
  182. LOGERROR("Failed to connect to server " + address + ":" + String(port));
  183. SendEvent(E_CONNECTFAILED);
  184. return false;
  185. }
  186. }
  187. void Network::Disconnect(int waitMSec)
  188. {
  189. if (!serverConnection_)
  190. return;
  191. PROFILE(Disconnect);
  192. serverConnection_->Disconnect(waitMSec);
  193. }
  194. bool Network::StartServer(unsigned short port)
  195. {
  196. if (IsServerRunning())
  197. return true;
  198. PROFILE(StartServer);
  199. /// \todo Investigate why server fails to restart after stopping when false is specified for reuse
  200. if (network_->StartServer(port, kNet::SocketOverUDP, this, true) != 0)
  201. {
  202. LOGINFO("Started server on port " + String(port));
  203. return true;
  204. }
  205. else
  206. {
  207. LOGERROR("Failed to start server on port " + String(port));
  208. return false;
  209. }
  210. }
  211. void Network::StopServer()
  212. {
  213. if (!IsServerRunning())
  214. return;
  215. PROFILE(StopServer);
  216. clientConnections_.Clear();
  217. network_->StopServer();
  218. LOGINFO("Stopped server");
  219. }
  220. void Network::BroadcastMessage(int msgID, bool reliable, bool inOrder, const VectorBuffer& msg, unsigned priority,
  221. unsigned contentID)
  222. {
  223. BroadcastMessage(msgID, reliable, inOrder, msg.GetData(), msg.GetSize(), priority, contentID);
  224. }
  225. void Network::BroadcastMessage(int msgID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes,
  226. unsigned priority, unsigned contentID)
  227. {
  228. // Make sure not to use kNet internal message ID's
  229. if (msgID <= 0x4 || msgID >= 0x3ffffffe)
  230. {
  231. LOGERROR("Can not send message with reserved ID");
  232. return;
  233. }
  234. kNet::NetworkServer* server = network_->GetServer();
  235. if (server)
  236. server->BroadcastMessage(msgID, reliable, inOrder, priority, contentID, (const char*)data, numBytes);
  237. else
  238. LOGERROR("Server not running, can not broadcast messages");
  239. }
  240. void Network::BroadcastRemoteEvent(StringHash eventType, bool inOrder, const VariantMap& eventData)
  241. {
  242. for (HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Begin();
  243. i != clientConnections_.End(); ++i)
  244. i->second_->SendRemoteEvent(eventType, inOrder, eventData);
  245. }
  246. void Network::BroadcastRemoteEvent(Scene* scene, StringHash eventType, bool inOrder, const VariantMap& eventData)
  247. {
  248. for (HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Begin();
  249. i != clientConnections_.End(); ++i)
  250. {
  251. if (i->second_->GetScene() == scene)
  252. i->second_->SendRemoteEvent(eventType, inOrder, eventData);
  253. }
  254. }
  255. void Network::BroadcastRemoteEvent(Node* receiver, StringHash eventType, bool inOrder, const VariantMap& eventData)
  256. {
  257. if (!receiver)
  258. {
  259. LOGERROR("Null node for remote node event");
  260. return;
  261. }
  262. if (receiver->GetID() >= FIRST_LOCAL_ID)
  263. {
  264. LOGERROR("Node has a local ID, can not send remote node event");
  265. return;
  266. }
  267. Scene* scene = receiver->GetScene();
  268. for (HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Begin();
  269. i != clientConnections_.End(); ++i)
  270. {
  271. if (i->second_->GetScene() == scene)
  272. i->second_->SendRemoteEvent(receiver, eventType, inOrder, eventData);
  273. }
  274. }
  275. void Network::SetUpdateFps(int fps)
  276. {
  277. updateFps_ = Max(fps, 1);
  278. updateInterval_ = 1.0f / (float)updateFps_;
  279. updateAcc_ = 0.0f;
  280. }
  281. void Network::RegisterRemoteEvent(StringHash eventType)
  282. {
  283. allowedRemoteEvents_.Insert(eventType);
  284. }
  285. void Network::UnregisterRemoteEvent(StringHash eventType)
  286. {
  287. allowedRemoteEvents_.Erase(eventType);
  288. }
  289. void Network::UnregisterAllRemoteEvents()
  290. {
  291. allowedRemoteEvents_.Clear();
  292. }
  293. void Network::SetPackageCacheDir(const String& path)
  294. {
  295. packageCacheDir_ = AddTrailingSlash(path);
  296. }
  297. Connection* Network::GetConnection(kNet::MessageConnection* connection) const
  298. {
  299. HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Find(connection);
  300. if (i != clientConnections_.End())
  301. return i->second_;
  302. else if (serverConnection_ && serverConnection_->GetMessageConnection() == connection)
  303. return serverConnection_;
  304. else
  305. return 0;
  306. }
  307. Connection* Network::GetServerConnection() const
  308. {
  309. return serverConnection_;
  310. }
  311. bool Network::IsServerRunning() const
  312. {
  313. return network_->GetServer();
  314. }
  315. bool Network::CheckRemoteEvent(StringHash eventType) const
  316. {
  317. return allowedRemoteEvents_.Empty() || allowedRemoteEvents_.Contains(eventType);
  318. }
  319. void Network::Update(float timeStep)
  320. {
  321. PROFILE(UpdateNetwork);
  322. // Process server connection if it exists
  323. if (serverConnection_)
  324. {
  325. kNet::MessageConnection* connection = serverConnection_->GetMessageConnection();
  326. // Receive new messages
  327. connection->Process();
  328. // Process latest data messages waiting for the correct nodes or components to be created
  329. serverConnection_->ProcessPendingLatestData();
  330. // Check for state transitions
  331. kNet::ConnectionState state = connection->GetConnectionState();
  332. if (serverConnection_->IsConnectPending() && state == kNet::ConnectionOK)
  333. OnServerConnected();
  334. else if (state == kNet::ConnectionPeerClosed)
  335. serverConnection_->Disconnect();
  336. else if (state == kNet::ConnectionClosed)
  337. OnServerDisconnected();
  338. }
  339. // Process the network server if started
  340. kNet::SharedPtr<kNet::NetworkServer> server = network_->GetServer();
  341. if (server)
  342. server->Process();
  343. }
  344. void Network::PostUpdate(float timeStep)
  345. {
  346. PROFILE(PostUpdateNetwork);
  347. // Check if periodic update should happen now
  348. updateAcc_ += timeStep;
  349. bool updateNow = updateAcc_ >= updateInterval_;
  350. if (updateNow)
  351. {
  352. // Notify of the impending update to allow for example updated client controls to be set
  353. SendEvent(E_NETWORKUPDATE);
  354. updateAcc_ = fmodf(updateAcc_, updateInterval_);
  355. if (IsServerRunning())
  356. {
  357. // Send server updates for each client connection
  358. for (HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Begin();
  359. i != clientConnections_.End(); ++i)
  360. {
  361. i->second_->SendServerUpdate(frameNumber_);
  362. i->second_->SendRemoteEvents();
  363. i->second_->SendPackages();
  364. }
  365. }
  366. if (serverConnection_)
  367. {
  368. // Send the client update
  369. serverConnection_->SendClientUpdate();
  370. serverConnection_->SendRemoteEvents();
  371. }
  372. // Notify that the update was sent
  373. SendEvent(E_NETWORKUPDATESENT);
  374. // Increment server frame number. Wrap to 1 as 0 means "update never sent" for Serializables
  375. ++frameNumber_;
  376. if (!frameNumber_)
  377. ++frameNumber_;
  378. }
  379. }
  380. void Network::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  381. {
  382. using namespace BeginFrame;
  383. Update(eventData[P_TIMESTEP].GetFloat());
  384. }
  385. void Network::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  386. {
  387. using namespace RenderUpdate;
  388. PostUpdate(eventData[P_TIMESTEP].GetFloat());
  389. }
  390. void Network::OnServerConnected()
  391. {
  392. serverConnection_->SetConnectPending(false);
  393. LOGINFO("Connected to server");
  394. // Send the identity map now
  395. VectorBuffer msg;
  396. msg.WriteVariantMap(serverConnection_->GetIdentity());
  397. serverConnection_->SendMessage(MSG_IDENTITY, true, true, msg, NET_HIGH_PRIORITY);
  398. SendEvent(E_SERVERCONNECTED);
  399. }
  400. void Network::OnServerDisconnected()
  401. {
  402. // Differentiate between failed connection, and disconnection
  403. bool failedConnect = serverConnection_ && serverConnection_->IsConnectPending();
  404. if (!failedConnect)
  405. {
  406. LOGINFO("Disconnected from server");
  407. SendEvent(E_SERVERDISCONNECTED);
  408. }
  409. else
  410. {
  411. LOGERROR("Failed to connect to server");
  412. SendEvent(E_CONNECTFAILED);
  413. }
  414. serverConnection_.Reset();
  415. }
  416. void RegisterNetworkLibrary(Context* context)
  417. {
  418. NetworkPriority::RegisterObject(context);
  419. }