Network.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Oorni
  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. namespace Urho3D
  39. {
  40. static const int DEFAULT_UPDATE_FPS = 30;
  41. OBJECTTYPESTATIC(Network);
  42. Network::Network(Context* context) :
  43. Object(context),
  44. updateFps_(DEFAULT_UPDATE_FPS),
  45. updateInterval_(1.0f / (float)DEFAULT_UPDATE_FPS),
  46. updateAcc_(0.0f)
  47. {
  48. network_ = new kNet::Network();
  49. SubscribeToEvent(E_BEGINFRAME, HANDLER(Network, HandleBeginFrame));
  50. SubscribeToEvent(E_RENDERUPDATE, HANDLER(Network, HandleRenderUpdate));
  51. }
  52. Network::~Network()
  53. {
  54. // If server connection exists, disconnect, but do not send an event because we are shutting down
  55. Disconnect(100);
  56. serverConnection_.Reset();
  57. clientConnections_.Clear();
  58. delete network_;
  59. network_ = 0;
  60. }
  61. void Network::HandleMessage(kNet::MessageConnection *source, kNet::packet_id_t packetId, kNet::message_id_t msgId, const char *data, size_t numBytes)
  62. {
  63. // Only process messages from known sources
  64. Connection* connection = GetConnection(source);
  65. if (connection)
  66. {
  67. MemoryBuffer msg(data, numBytes);
  68. switch (msgId)
  69. {
  70. case MSG_IDENTITY:
  71. connection->ProcessIdentity(msgId, msg);
  72. return;
  73. case MSG_CONTROLS:
  74. connection->ProcessControls(msgId, msg);
  75. return;
  76. case MSG_SCENELOADED:
  77. connection->ProcessSceneLoaded(msgId, msg);
  78. return;
  79. case MSG_REQUESTPACKAGE:
  80. case MSG_PACKAGEDATA:
  81. connection->ProcessPackageDownload(msgId, msg);
  82. return;
  83. case MSG_LOADSCENE:
  84. connection->ProcessLoadScene(msgId, msg);
  85. return;
  86. case MSG_SCENECHECKSUMERROR:
  87. connection->ProcessSceneChecksumError(msgId, msg);
  88. return;
  89. case MSG_CREATENODE:
  90. case MSG_NODEDELTAUPDATE:
  91. case MSG_NODELATESTDATA:
  92. case MSG_REMOVENODE:
  93. case MSG_CREATECOMPONENT:
  94. case MSG_COMPONENTDELTAUPDATE:
  95. case MSG_COMPONENTLATESTDATA:
  96. case MSG_REMOVECOMPONENT:
  97. connection->ProcessSceneUpdate(msgId, msg);
  98. return;
  99. case MSG_REMOTEEVENT:
  100. case MSG_REMOTENODEEVENT:
  101. connection->ProcessRemoteEvent(msgId, msg);
  102. return;
  103. }
  104. // If message was not handled internally, forward as an event
  105. using namespace NetworkMessage;
  106. VariantMap eventData;
  107. eventData[P_CONNECTION] = (void*)connection;
  108. eventData[P_MESSAGEID] = (int)msgId;
  109. eventData[P_DATA].SetBuffer(msg.GetData(), msg.GetSize());
  110. connection->SendEvent(E_NETWORKMESSAGE, eventData);
  111. }
  112. else
  113. LOGWARNING("Discarding message from unknown MessageConnection " + ToString((void*)source));
  114. }
  115. u32 Network::ComputeContentID(kNet::message_id_t msgId, const char* data, size_t numBytes)
  116. {
  117. switch (msgId)
  118. {
  119. case MSG_CONTROLS:
  120. // Return fixed content ID for controls
  121. return CONTROLS_CONTENT_ID;
  122. case MSG_NODELATESTDATA:
  123. case MSG_COMPONENTLATESTDATA:
  124. {
  125. // Return the node or component ID, which is first in the message
  126. MemoryBuffer msg(data, numBytes);
  127. return msg.ReadNetID();
  128. }
  129. default:
  130. // By default return no content ID
  131. return 0;
  132. }
  133. }
  134. void Network::NewConnectionEstablished(kNet::MessageConnection* connection)
  135. {
  136. connection->RegisterInboundMessageHandler(this);
  137. // Create a new client connection corresponding to this MessageConnection
  138. SharedPtr<Connection> newConnection(new Connection(context_, true, kNet::SharedPtr<kNet::MessageConnection>(connection)));
  139. clientConnections_[connection] = newConnection;
  140. LOGINFO("Client " + newConnection->ToString() + " connected");
  141. using namespace ClientConnected;
  142. VariantMap eventData;
  143. eventData[P_CONNECTION] = (void*)newConnection;
  144. newConnection->SendEvent(E_CLIENTCONNECTED, eventData);
  145. }
  146. void Network::ClientDisconnected(kNet::MessageConnection* connection)
  147. {
  148. connection->Disconnect(0);
  149. // Remove the client connection that corresponds to this MessageConnection
  150. HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::Iterator i = clientConnections_.Find(connection);
  151. if (i != clientConnections_.End())
  152. {
  153. Connection* connection = i->second_;
  154. LOGINFO("Client " + connection->ToString() + " disconnected");
  155. using namespace ClientDisconnected;
  156. VariantMap eventData;
  157. eventData[P_CONNECTION] = (void*)connection;
  158. connection->SendEvent(E_CLIENTDISCONNECTED, eventData);
  159. clientConnections_.Erase(i);
  160. }
  161. }
  162. bool Network::Connect(const String& address, unsigned short port, Scene* scene, const VariantMap& identity)
  163. {
  164. PROFILE(Connect);
  165. // If a previous connection already exists, disconnect it and wait for some time for the connection to terminate
  166. if (serverConnection_)
  167. {
  168. serverConnection_->Disconnect(100);
  169. OnServerDisconnected();
  170. }
  171. kNet::SharedPtr<kNet::MessageConnection> connection = network_->Connect(address.CString(), port, kNet::SocketOverUDP, this);
  172. if (connection)
  173. {
  174. LOGINFO("Connecting to server " + address + ":" + String(port));
  175. serverConnection_ = new Connection(context_, false, connection);
  176. serverConnection_->SetScene(scene);
  177. serverConnection_->SetIdentity(identity);
  178. serverConnection_->SetConnectPending(true);
  179. return true;
  180. }
  181. else
  182. {
  183. LOGERROR("Failed to connect to server " + address + ":" + String(port));
  184. SendEvent(E_CONNECTFAILED);
  185. return false;
  186. }
  187. }
  188. void Network::Disconnect(int waitMSec)
  189. {
  190. if (!serverConnection_)
  191. return;
  192. PROFILE(Disconnect);
  193. serverConnection_->Disconnect(waitMSec);
  194. }
  195. bool Network::StartServer(unsigned short port)
  196. {
  197. if (IsServerRunning())
  198. return true;
  199. PROFILE(StartServer);
  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 contentID)
  221. {
  222. BroadcastMessage(msgID, reliable, inOrder, msg.GetData(), msg.GetSize(), contentID);
  223. }
  224. void Network::BroadcastMessage(int msgID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes,
  225. 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, 0, 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 (HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::Iterator 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 (HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::Iterator 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* node, StringHash eventType, bool inOrder, const VariantMap& eventData)
  255. {
  256. if (!node)
  257. {
  258. LOGERROR("Null sender node for remote node event");
  259. return;
  260. }
  261. if (node->GetID() >= FIRST_LOCAL_ID)
  262. {
  263. LOGERROR("Sender node has a local ID, can not send remote node event");
  264. return;
  265. }
  266. Scene* scene = node->GetScene();
  267. for (HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::Iterator i = clientConnections_.Begin();
  268. i != clientConnections_.End(); ++i)
  269. {
  270. if (i->second_->GetScene() == scene)
  271. i->second_->SendRemoteEvent(node, 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. HashMap<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. Vector<SharedPtr<Connection> > Network::GetClientConnections() const
  311. {
  312. Vector<SharedPtr<Connection> > ret;
  313. for (HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Begin();
  314. i != clientConnections_.End(); ++i)
  315. ret.Push(i->second_);
  316. return ret;
  317. }
  318. bool Network::IsServerRunning() const
  319. {
  320. return network_->GetServer();
  321. }
  322. bool Network::CheckRemoteEvent(StringHash eventType) const
  323. {
  324. return allowedRemoteEvents_.Empty() || allowedRemoteEvents_.Contains(eventType);
  325. }
  326. void Network::Update(float timeStep)
  327. {
  328. PROFILE(UpdateNetwork);
  329. // Process server connection if it exists
  330. if (serverConnection_)
  331. {
  332. kNet::MessageConnection* connection = serverConnection_->GetMessageConnection();
  333. // Receive new messages
  334. connection->Process();
  335. // Process latest data messages waiting for the correct nodes or components to be created
  336. serverConnection_->ProcessPendingLatestData();
  337. // Check for state transitions
  338. kNet::ConnectionState state = connection->GetConnectionState();
  339. if (serverConnection_->IsConnectPending() && state == kNet::ConnectionOK)
  340. OnServerConnected();
  341. else if (state == kNet::ConnectionPeerClosed)
  342. serverConnection_->Disconnect();
  343. else if (state == kNet::ConnectionClosed)
  344. OnServerDisconnected();
  345. }
  346. // Process the network server if started
  347. kNet::SharedPtr<kNet::NetworkServer> server = network_->GetServer();
  348. if (server)
  349. server->Process();
  350. }
  351. void Network::PostUpdate(float timeStep)
  352. {
  353. PROFILE(PostUpdateNetwork);
  354. // Check if periodic update should happen now
  355. updateAcc_ += timeStep;
  356. bool updateNow = updateAcc_ >= updateInterval_;
  357. if (updateNow)
  358. {
  359. // Notify of the impending update to allow for example updated client controls to be set
  360. SendEvent(E_NETWORKUPDATE);
  361. updateAcc_ = fmodf(updateAcc_, updateInterval_);
  362. if (IsServerRunning())
  363. {
  364. // Collect and prepare all networked scenes
  365. {
  366. PROFILE(PrepareServerUpdate);
  367. networkScenes_.Clear();
  368. for (HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::Iterator i = clientConnections_.Begin();
  369. i != clientConnections_.End(); ++i)
  370. {
  371. Scene* scene = i->second_->GetScene();
  372. if (scene)
  373. networkScenes_.Insert(scene);
  374. }
  375. for (HashSet<Scene*>::ConstIterator i = networkScenes_.Begin(); i != networkScenes_.End(); ++i)
  376. (*i)->PrepareNetworkUpdate();
  377. }
  378. {
  379. PROFILE(SendServerUpdate);
  380. // Then send server updates for each client connection
  381. for (HashMap<kNet::MessageConnection*, SharedPtr<Connection> >::Iterator i = clientConnections_.Begin();
  382. i != clientConnections_.End(); ++i)
  383. {
  384. i->second_->SendServerUpdate();
  385. i->second_->SendRemoteEvents();
  386. i->second_->SendPackages();
  387. }
  388. }
  389. }
  390. if (serverConnection_)
  391. {
  392. // Send the client update
  393. serverConnection_->SendClientUpdate();
  394. serverConnection_->SendRemoteEvents();
  395. }
  396. // Notify that the update was sent
  397. SendEvent(E_NETWORKUPDATESENT);
  398. }
  399. }
  400. void Network::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  401. {
  402. using namespace BeginFrame;
  403. Update(eventData[P_TIMESTEP].GetFloat());
  404. }
  405. void Network::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  406. {
  407. using namespace RenderUpdate;
  408. PostUpdate(eventData[P_TIMESTEP].GetFloat());
  409. }
  410. void Network::OnServerConnected()
  411. {
  412. serverConnection_->SetConnectPending(false);
  413. LOGINFO("Connected to server");
  414. // Send the identity map now
  415. VectorBuffer msg;
  416. msg.WriteVariantMap(serverConnection_->GetIdentity());
  417. serverConnection_->SendMessage(MSG_IDENTITY, true, true, msg);
  418. SendEvent(E_SERVERCONNECTED);
  419. }
  420. void Network::OnServerDisconnected()
  421. {
  422. // Differentiate between failed connection, and disconnection
  423. bool failedConnect = serverConnection_ && serverConnection_->IsConnectPending();
  424. if (!failedConnect)
  425. {
  426. LOGINFO("Disconnected from server");
  427. SendEvent(E_SERVERDISCONNECTED);
  428. }
  429. else
  430. {
  431. LOGERROR("Failed to connect to server");
  432. SendEvent(E_CONNECTFAILED);
  433. }
  434. serverConnection_.Reset();
  435. }
  436. void RegisterNetworkLibrary(Context* context)
  437. {
  438. NetworkPriority::RegisterObject(context);
  439. }
  440. }