Network.cpp 15 KB

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