Network.cpp 15 KB

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