Network.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 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 "Profiler.h"
  32. #include "Protocol.h"
  33. #include "Scene.h"
  34. #include "StringUtils.h"
  35. #include <kNet.h>
  36. #include "DebugNew.h"
  37. static const int DEFAULT_UPDATE_FPS = 25;
  38. OBJECTTYPESTATIC(Network);
  39. Network::Network(Context* context) :
  40. Object(context),
  41. updateFps_(DEFAULT_UPDATE_FPS),
  42. updateInterval_(1.0f / (float)DEFAULT_UPDATE_FPS),
  43. updateAcc_(0.0f)
  44. {
  45. network_ = new kNet::Network();
  46. SubscribeToEvent(E_BEGINFRAME, HANDLER(Network, HandleBeginFrame));
  47. SubscribeToEvent(E_RENDERUPDATE, HANDLER(Network, HandleRenderUpdate));
  48. }
  49. Network::~Network()
  50. {
  51. // If server connection exists, disconnect, but do not send an event because we are shutting down
  52. Disconnect(100);
  53. serverConnection_.Reset();
  54. clientConnections_.Clear();
  55. delete network_;
  56. network_ = 0;
  57. }
  58. void Network::HandleMessage(kNet::MessageConnection* source, kNet::message_id_t id, const char* data, size_t numBytes)
  59. {
  60. // Only process messages from known sources
  61. Connection* connection = GetConnection(source);
  62. if (connection)
  63. {
  64. MemoryBuffer msg(data, numBytes);
  65. switch (id)
  66. {
  67. case MSG_IDENTITY:
  68. connection->ProcessIdentity(id, msg);
  69. return;
  70. case MSG_CONTROLS:
  71. connection->ProcessControls(id, msg);
  72. return;
  73. case MSG_SCENELOADED:
  74. connection->ProcessSceneLoaded(id, msg);
  75. return;
  76. case MSG_REQUESTPACKAGE:
  77. case MSG_PACKAGEDATA:
  78. connection->ProcessPackageDownload(id, msg);
  79. return;
  80. case MSG_LOADSCENE:
  81. connection->ProcessLoadScene(id, msg);
  82. return;
  83. case MSG_SCENECHECKSUMERROR:
  84. connection->ProcessSceneChecksumError(id, msg);
  85. return;
  86. case MSG_CREATENODE:
  87. case MSG_NODEDELTAUPDATE:
  88. case MSG_NODELATESTDATA:
  89. case MSG_REMOVENODE:
  90. case MSG_CREATECOMPONENT:
  91. case MSG_COMPONENTDELTAUPDATE:
  92. case MSG_COMPONENTLATESTDATA:
  93. case MSG_REMOVECOMPONENT:
  94. connection->ProcessSceneUpdate(id, msg);
  95. return;
  96. case MSG_REMOTEEVENT:
  97. case MSG_REMOTENODEEVENT:
  98. connection->ProcessRemoteEvent(id, msg);
  99. return;
  100. }
  101. // If message was not handled internally, forward as an event
  102. using namespace NetworkMessage;
  103. VariantMap eventData;
  104. eventData[P_CONNECTION] = (void*)connection;
  105. eventData[P_MESSAGEID] = (int)id;
  106. eventData[P_DATA].SetBuffer(msg.GetData(), msg.GetSize());
  107. connection->SendEvent(E_NETWORKMESSAGE, eventData);
  108. }
  109. else
  110. LOGWARNING("Discarding message from unknown MessageConnection " + ToString((void*)source));
  111. }
  112. u32 Network::ComputeContentID(kNet::message_id_t id, const char* data, size_t numBytes)
  113. {
  114. switch (id)
  115. {
  116. case MSG_CONTROLS:
  117. // Return fixed content ID for controls
  118. return CONTROLS_CONTENT_ID;
  119. case MSG_NODELATESTDATA:
  120. case MSG_COMPONENTLATESTDATA:
  121. {
  122. // Return the node or component ID, which is first in the message
  123. MemoryBuffer msg(data, numBytes);
  124. return msg.ReadVLE();
  125. }
  126. default:
  127. // By default return no content ID
  128. return 0;
  129. }
  130. }
  131. void Network::NewConnectionEstablished(kNet::MessageConnection* connection)
  132. {
  133. connection->RegisterInboundMessageHandler(this);
  134. // Create a new client connection corresponding to this MessageConnection
  135. Connection* newConnection = new Connection(context_, true, kNet::SharedPtr<kNet::MessageConnection>(connection));
  136. clientConnections_[connection] = newConnection;
  137. LOGINFO("Client " + newConnection->ToString() + " connected");
  138. using namespace ClientConnected;
  139. VariantMap eventData;
  140. eventData[P_CONNECTION] = (void*)newConnection;
  141. newConnection->SendEvent(E_CLIENTCONNECTED, eventData);
  142. }
  143. void Network::ClientDisconnected(kNet::MessageConnection* connection)
  144. {
  145. connection->Disconnect(0);
  146. // Remove the client connection that corresponds to this MessageConnection
  147. Map<kNet::MessageConnection*, SharedPtr<Connection> >::Iterator i = clientConnections_.Find(connection);
  148. if (i != clientConnections_.End())
  149. {
  150. Connection* connection = i->second_;
  151. LOGINFO("Client " + connection->ToString() + " disconnected");
  152. using namespace ClientDisconnected;
  153. VariantMap eventData;
  154. eventData[P_CONNECTION] = (void*)connection;
  155. connection->SendEvent(E_CLIENTDISCONNECTED, eventData);
  156. clientConnections_.Erase(i);
  157. }
  158. }
  159. bool Network::Connect(const String& address, unsigned short port, Scene* scene, const VariantMap& identity)
  160. {
  161. PROFILE(Connect);
  162. // If a previous connection already exists, disconnect it and wait for some time for the connection to terminate
  163. if (serverConnection_)
  164. {
  165. serverConnection_->Disconnect(100);
  166. OnServerDisconnected();
  167. }
  168. kNet::SharedPtr<kNet::MessageConnection> connection = network_->Connect(address.CString(), port, kNet::SocketOverUDP, this);
  169. if (connection)
  170. {
  171. LOGINFO("Connecting to server " + address + ":" + String(port));
  172. serverConnection_ = new Connection(context_, false, connection);
  173. serverConnection_->SetScene(scene);
  174. serverConnection_->SetIdentity(identity);
  175. serverConnection_->SetConnectPending(true);
  176. return true;
  177. }
  178. else
  179. {
  180. LOGERROR("Failed to connect to server " + address + ":" + String(port));
  181. SendEvent(E_CONNECTFAILED);
  182. return false;
  183. }
  184. }
  185. void Network::Disconnect(int waitMSec)
  186. {
  187. if (!serverConnection_)
  188. return;
  189. PROFILE(Disconnect);
  190. serverConnection_->Disconnect(waitMSec);
  191. }
  192. bool Network::StartServer(unsigned short port)
  193. {
  194. if (IsServerRunning())
  195. return true;
  196. PROFILE(StartServer);
  197. /// \todo Investigate why server fails to restart after stopping when false is specified for reuse
  198. if (network_->StartServer(port, kNet::SocketOverUDP, this, true) != 0)
  199. {
  200. LOGINFO("Started server on port " + String(port));
  201. return true;
  202. }
  203. else
  204. {
  205. LOGERROR("Failed to start server on port " + String(port));
  206. return false;
  207. }
  208. }
  209. void Network::StopServer()
  210. {
  211. if (!IsServerRunning())
  212. return;
  213. PROFILE(StopServer);
  214. clientConnections_.Clear();
  215. network_->StopServer();
  216. LOGINFO("Stopped server");
  217. }
  218. void Network::BroadcastMessage(int msgID, bool reliable, bool inOrder, const VectorBuffer& msg, unsigned priority, unsigned contentID)
  219. {
  220. BroadcastMessage(msgID, reliable, inOrder, msg.GetData(), msg.GetSize(), priority, contentID);
  221. }
  222. void Network::BroadcastMessage(int msgID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes, unsigned priority, unsigned contentID)
  223. {
  224. // Make sure not to use kNet internal message ID's
  225. if (msgID <= 0x4 || msgID >= 0x3ffffffe)
  226. {
  227. LOGERROR("Can not send message with reserved ID");
  228. return;
  229. }
  230. kNet::NetworkServer* server = network_->GetServer();
  231. if (server)
  232. server->BroadcastMessage(msgID, reliable, inOrder, priority, contentID, (const char*)data, numBytes);
  233. else
  234. LOGERROR("Server not running, can not broadcast messages");
  235. }
  236. void Network::BroadcastRemoteEvent(StringHash eventType, bool inOrder, const VariantMap& eventData)
  237. {
  238. for (Map<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Begin();
  239. i != clientConnections_.End(); ++i)
  240. i->second_->SendRemoteEvent(eventType, inOrder, eventData);
  241. }
  242. void Network::BroadcastRemoteEvent(Scene* scene, StringHash eventType, bool inOrder, const VariantMap& eventData)
  243. {
  244. for (Map<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Begin();
  245. i != clientConnections_.End(); ++i)
  246. {
  247. if (i->second_->GetScene() == scene)
  248. i->second_->SendRemoteEvent(eventType, inOrder, eventData);
  249. }
  250. }
  251. void Network::BroadcastRemoteEvent(Node* receiver, StringHash eventType, bool inOrder, const VariantMap& eventData)
  252. {
  253. if (!receiver)
  254. {
  255. LOGERROR("Null node for remote node event");
  256. return;
  257. }
  258. if (receiver->GetID() >= FIRST_LOCAL_ID)
  259. {
  260. LOGERROR("Node has a local ID, can not send remote node event");
  261. return;
  262. }
  263. Scene* scene = receiver->GetScene();
  264. for (Map<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Begin();
  265. i != clientConnections_.End(); ++i)
  266. {
  267. if (i->second_->GetScene() == scene)
  268. i->second_->SendRemoteEvent(receiver, eventType, inOrder, eventData);
  269. }
  270. }
  271. void Network::SetUpdateFps(int fps)
  272. {
  273. updateFps_ = Max(fps, 1);
  274. updateInterval_ = 1.0f / (float)updateFps_;
  275. updateAcc_ = 0.0f;
  276. }
  277. void Network::RegisterRemoteEvent(StringHash eventType)
  278. {
  279. allowedRemoteEvents_.Insert(eventType);
  280. }
  281. void Network::UnregisterRemoteEvent(StringHash eventType)
  282. {
  283. allowedRemoteEvents_.Erase(eventType);
  284. }
  285. void Network::UnregisterAllRemoteEvents()
  286. {
  287. allowedRemoteEvents_.Clear();
  288. }
  289. void Network::SetPackageCacheDir(const String& path)
  290. {
  291. packageCacheDir_ = AddTrailingSlash(path);
  292. }
  293. Connection* Network::GetConnection(kNet::MessageConnection* connection) const
  294. {
  295. Map<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Find(connection);
  296. if (i != clientConnections_.End())
  297. return i->second_;
  298. else if (serverConnection_ && serverConnection_->GetMessageConnection() == connection)
  299. return serverConnection_;
  300. else
  301. return 0;
  302. }
  303. Connection* Network::GetServerConnection() const
  304. {
  305. return serverConnection_;
  306. }
  307. bool Network::IsServerRunning() const
  308. {
  309. return network_->GetServer();
  310. }
  311. bool Network::CheckRemoteEvent(StringHash eventType) const
  312. {
  313. return allowedRemoteEvents_.Empty() || allowedRemoteEvents_.Contains(eventType);
  314. }
  315. void Network::Update(float timeStep)
  316. {
  317. PROFILE(UpdateNetwork);
  318. // Process server connection if it exists
  319. if (serverConnection_)
  320. {
  321. kNet::MessageConnection* connection = serverConnection_->GetMessageConnection();
  322. // Receive new messages
  323. connection->Process();
  324. // Process latest data messages waiting for the correct nodes or components to be created
  325. serverConnection_->ProcessPendingLatestData();
  326. // Check for state transitions
  327. kNet::ConnectionState state = connection->GetConnectionState();
  328. if (serverConnection_->IsConnectPending() && state == kNet::ConnectionOK)
  329. OnServerConnected();
  330. else if (state == kNet::ConnectionPeerClosed)
  331. serverConnection_->Disconnect();
  332. else if (state == kNet::ConnectionClosed)
  333. OnServerDisconnected();
  334. }
  335. // Process the network server if started
  336. kNet::SharedPtr<kNet::NetworkServer> server = network_->GetServer();
  337. if (server)
  338. server->Process();
  339. }
  340. void Network::PostUpdate(float timeStep)
  341. {
  342. PROFILE(PostUpdateNetwork);
  343. // Check if periodic update should happen now
  344. updateAcc_ += timeStep;
  345. bool updateNow = updateAcc_ >= updateInterval_;
  346. if (updateNow)
  347. {
  348. // Notify of the impending update to allow for example updated client controls to be set
  349. SendEvent(E_NETWORKUPDATE);
  350. updateAcc_ = fmodf(updateAcc_, updateInterval_);
  351. if (IsServerRunning())
  352. {
  353. // Send server updates for each client connection
  354. for (Map<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Begin();
  355. i != clientConnections_.End(); ++i)
  356. {
  357. i->second_->SendServerUpdate();
  358. i->second_->SendRemoteEvents();
  359. }
  360. }
  361. if (serverConnection_)
  362. {
  363. // Send the client update
  364. serverConnection_->SendClientUpdate();
  365. serverConnection_->SendRemoteEvents();
  366. }
  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, NET_HIGH_PRIORITY);
  387. SendEvent(E_SERVERCONNECTED);
  388. }
  389. void Network::OnServerDisconnected()
  390. {
  391. // Differentiate between failed connection, and disconnection
  392. bool failedConnect = serverConnection_ && serverConnection_->IsConnectPending();
  393. if (!failedConnect)
  394. {
  395. LOGINFO("Disconnected from server");
  396. SendEvent(E_SERVERDISCONNECTED);
  397. }
  398. else
  399. {
  400. LOGERROR("Failed to connect to server");
  401. SendEvent(E_CONNECTFAILED);
  402. }
  403. serverConnection_.Reset();
  404. }