Network.cpp 15 KB

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