Network.cpp 16 KB

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