2
0

Network.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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::packet_id_t packetId, kNet::message_id_t msgId, 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 (msgId)
  67. {
  68. case MSG_IDENTITY:
  69. connection->ProcessIdentity(msgId, msg);
  70. return;
  71. case MSG_CONTROLS:
  72. connection->ProcessControls(msgId, msg);
  73. return;
  74. case MSG_SCENELOADED:
  75. connection->ProcessSceneLoaded(msgId, msg);
  76. return;
  77. case MSG_REQUESTPACKAGE:
  78. case MSG_PACKAGEDATA:
  79. connection->ProcessPackageDownload(msgId, msg);
  80. return;
  81. case MSG_LOADSCENE:
  82. connection->ProcessLoadScene(msgId, msg);
  83. return;
  84. case MSG_SCENECHECKSUMERROR:
  85. connection->ProcessSceneChecksumError(msgId, 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(msgId, msg);
  96. return;
  97. case MSG_REMOTEEVENT:
  98. case MSG_REMOTENODEEVENT:
  99. connection->ProcessRemoteEvent(msgId, 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)msgId;
  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 msgId, const char* data, size_t numBytes)
  114. {
  115. switch (msgId)
  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 contentID)
  220. {
  221. BroadcastMessage(msgID, reliable, inOrder, msg.GetData(), msg.GetSize(), contentID);
  222. }
  223. void Network::BroadcastMessage(int msgID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes,
  224. unsigned contentID)
  225. {
  226. // Make sure not to use kNet internal message ID's
  227. if (msgID <= 0x4 || msgID >= 0x3ffffffe)
  228. {
  229. LOGERROR("Can not send message with reserved ID");
  230. return;
  231. }
  232. kNet::NetworkServer* server = network_->GetServer();
  233. if (server)
  234. server->BroadcastMessage(msgID, reliable, inOrder, 0, contentID, (const char*)data, numBytes);
  235. else
  236. LOGERROR("Server not running, can not broadcast messages");
  237. }
  238. void Network::BroadcastRemoteEvent(StringHash eventType, bool inOrder, const VariantMap& eventData)
  239. {
  240. for (Map<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Begin();
  241. i != clientConnections_.End(); ++i)
  242. i->second_->SendRemoteEvent(eventType, inOrder, eventData);
  243. }
  244. void Network::BroadcastRemoteEvent(Scene* scene, StringHash eventType, bool inOrder, const VariantMap& eventData)
  245. {
  246. for (Map<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Begin();
  247. i != clientConnections_.End(); ++i)
  248. {
  249. if (i->second_->GetScene() == scene)
  250. i->second_->SendRemoteEvent(eventType, inOrder, eventData);
  251. }
  252. }
  253. void Network::BroadcastRemoteEvent(Node* receiver, StringHash eventType, bool inOrder, const VariantMap& eventData)
  254. {
  255. if (!receiver)
  256. {
  257. LOGERROR("Null node for remote node event");
  258. return;
  259. }
  260. if (receiver->GetID() >= FIRST_LOCAL_ID)
  261. {
  262. LOGERROR("Node has a local ID, can not send remote node event");
  263. return;
  264. }
  265. Scene* scene = receiver->GetScene();
  266. for (Map<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Begin();
  267. i != clientConnections_.End(); ++i)
  268. {
  269. if (i->second_->GetScene() == scene)
  270. i->second_->SendRemoteEvent(receiver, eventType, inOrder, eventData);
  271. }
  272. }
  273. void Network::SetUpdateFps(int fps)
  274. {
  275. updateFps_ = Max(fps, 1);
  276. updateInterval_ = 1.0f / (float)updateFps_;
  277. updateAcc_ = 0.0f;
  278. }
  279. void Network::RegisterRemoteEvent(StringHash eventType)
  280. {
  281. allowedRemoteEvents_.Insert(eventType);
  282. }
  283. void Network::UnregisterRemoteEvent(StringHash eventType)
  284. {
  285. allowedRemoteEvents_.Erase(eventType);
  286. }
  287. void Network::UnregisterAllRemoteEvents()
  288. {
  289. allowedRemoteEvents_.Clear();
  290. }
  291. void Network::SetPackageCacheDir(const String& path)
  292. {
  293. packageCacheDir_ = AddTrailingSlash(path);
  294. }
  295. Connection* Network::GetConnection(kNet::MessageConnection* connection) const
  296. {
  297. Map<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Find(connection);
  298. if (i != clientConnections_.End())
  299. return i->second_;
  300. else if (serverConnection_ && serverConnection_->GetMessageConnection() == connection)
  301. return serverConnection_;
  302. else
  303. return 0;
  304. }
  305. Connection* Network::GetServerConnection() const
  306. {
  307. return serverConnection_;
  308. }
  309. bool Network::IsServerRunning() const
  310. {
  311. return network_->GetServer();
  312. }
  313. bool Network::CheckRemoteEvent(StringHash eventType) const
  314. {
  315. return allowedRemoteEvents_.Empty() || allowedRemoteEvents_.Contains(eventType);
  316. }
  317. void Network::Update(float timeStep)
  318. {
  319. PROFILE(UpdateNetwork);
  320. // Process server connection if it exists
  321. if (serverConnection_)
  322. {
  323. kNet::MessageConnection* connection = serverConnection_->GetMessageConnection();
  324. // Receive new messages
  325. connection->Process();
  326. // Process latest data messages waiting for the correct nodes or components to be created
  327. serverConnection_->ProcessPendingLatestData();
  328. // Check for state transitions
  329. kNet::ConnectionState state = connection->GetConnectionState();
  330. if (serverConnection_->IsConnectPending() && state == kNet::ConnectionOK)
  331. OnServerConnected();
  332. else if (state == kNet::ConnectionPeerClosed)
  333. serverConnection_->Disconnect();
  334. else if (state == kNet::ConnectionClosed)
  335. OnServerDisconnected();
  336. }
  337. // Process the network server if started
  338. kNet::SharedPtr<kNet::NetworkServer> server = network_->GetServer();
  339. if (server)
  340. server->Process();
  341. }
  342. void Network::PostUpdate(float timeStep)
  343. {
  344. PROFILE(PostUpdateNetwork);
  345. // Check if periodic update should happen now
  346. updateAcc_ += timeStep;
  347. bool updateNow = updateAcc_ >= updateInterval_;
  348. if (updateNow)
  349. {
  350. // Notify of the impending update to allow for example updated client controls to be set
  351. SendEvent(E_NETWORKUPDATE);
  352. updateAcc_ = fmodf(updateAcc_, updateInterval_);
  353. if (IsServerRunning())
  354. {
  355. // Collect and prepare all networked scenes
  356. {
  357. PROFILE(PrepareServerUpdate);
  358. networkScenes_.Clear();
  359. for (Map<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Begin();
  360. i != clientConnections_.End(); ++i)
  361. {
  362. Scene* scene = i->second_->GetScene();
  363. if (scene)
  364. networkScenes_.Insert(scene);
  365. }
  366. for (HashSet<Scene*>::ConstIterator i = networkScenes_.Begin(); i != networkScenes_.End(); ++i)
  367. (*i)->PrepareNetworkUpdate();
  368. }
  369. {
  370. PROFILE(SendServerUpdate);
  371. // Then send server updates for each client connection
  372. for (Map<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Begin();
  373. i != clientConnections_.End(); ++i)
  374. {
  375. i->second_->SendServerUpdate();
  376. i->second_->SendRemoteEvents();
  377. i->second_->SendPackages();
  378. }
  379. }
  380. }
  381. if (serverConnection_)
  382. {
  383. // Send the client update
  384. serverConnection_->SendClientUpdate();
  385. serverConnection_->SendRemoteEvents();
  386. }
  387. // Notify that the update was sent
  388. SendEvent(E_NETWORKUPDATESENT);
  389. }
  390. }
  391. void Network::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  392. {
  393. using namespace BeginFrame;
  394. Update(eventData[P_TIMESTEP].GetFloat());
  395. }
  396. void Network::HandleRenderUpdate(StringHash eventType, VariantMap& eventData)
  397. {
  398. using namespace RenderUpdate;
  399. PostUpdate(eventData[P_TIMESTEP].GetFloat());
  400. }
  401. void Network::OnServerConnected()
  402. {
  403. serverConnection_->SetConnectPending(false);
  404. LOGINFO("Connected to server");
  405. // Send the identity map now
  406. VectorBuffer msg;
  407. msg.WriteVariantMap(serverConnection_->GetIdentity());
  408. serverConnection_->SendMessage(MSG_IDENTITY, true, true, msg);
  409. SendEvent(E_SERVERCONNECTED);
  410. }
  411. void Network::OnServerDisconnected()
  412. {
  413. // Differentiate between failed connection, and disconnection
  414. bool failedConnect = serverConnection_ && serverConnection_->IsConnectPending();
  415. if (!failedConnect)
  416. {
  417. LOGINFO("Disconnected from server");
  418. SendEvent(E_SERVERDISCONNECTED);
  419. }
  420. else
  421. {
  422. LOGERROR("Failed to connect to server");
  423. SendEvent(E_CONNECTFAILED);
  424. }
  425. serverConnection_.Reset();
  426. }
  427. void RegisterNetworkLibrary(Context* context)
  428. {
  429. NetworkPriority::RegisterObject(context);
  430. }