Network.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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)
  217. {
  218. BroadcastMessage(msgID, 0, reliable, inOrder, msg.GetData(), msg.GetSize());
  219. }
  220. void Network::BroadcastMessage(int msgID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes)
  221. {
  222. BroadcastMessage(msgID, 0, reliable, inOrder, data, numBytes);
  223. }
  224. void Network::BroadcastMessage(int msgID, unsigned contentID, bool reliable, bool inOrder, const VectorBuffer& msg)
  225. {
  226. BroadcastMessage(msgID, contentID, reliable, inOrder, msg.GetData(), msg.GetSize());
  227. }
  228. void Network::BroadcastMessage(int msgID, unsigned contentID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes)
  229. {
  230. // Make sure not to use kNet internal message ID's
  231. if (msgID <= 0x4 || msgID >= 0x3ffffffe)
  232. {
  233. LOGERROR("Can not send message with reserved ID");
  234. return;
  235. }
  236. kNet::NetworkServer* server = network_->GetServer();
  237. if (server)
  238. server->BroadcastMessage(msgID, reliable, inOrder, DEFAULT_MSG_PRIORITY, contentID, (const char*)data, numBytes);
  239. else
  240. LOGERROR("Server not running, can not broadcast messages");
  241. }
  242. void Network::BroadcastRemoteEvent(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. i->second_->SendRemoteEvent(eventType, inOrder, eventData);
  247. }
  248. void Network::BroadcastRemoteEvent(Scene* scene, StringHash eventType, bool inOrder, const VariantMap& eventData)
  249. {
  250. for (Map<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Begin();
  251. i != clientConnections_.End(); ++i)
  252. {
  253. if (i->second_->GetScene() == scene)
  254. i->second_->SendRemoteEvent(eventType, inOrder, eventData);
  255. }
  256. }
  257. void Network::BroadcastRemoteEvent(Node* receiver, StringHash eventType, bool inOrder, const VariantMap& eventData)
  258. {
  259. if (!receiver)
  260. {
  261. LOGERROR("Null node for remote node event");
  262. return;
  263. }
  264. if (receiver->GetID() >= FIRST_LOCAL_ID)
  265. {
  266. LOGERROR("Node has a local ID, can not send remote node event");
  267. return;
  268. }
  269. Scene* scene = receiver->GetScene();
  270. for (Map<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Begin();
  271. i != clientConnections_.End(); ++i)
  272. {
  273. if (i->second_->GetScene() == scene)
  274. i->second_->SendRemoteEvent(receiver, eventType, inOrder, eventData);
  275. }
  276. }
  277. void Network::SetUpdateFps(int fps)
  278. {
  279. updateFps_ = Max(fps, 1);
  280. updateInterval_ = 1.0f / (float)updateFps_;
  281. updateAcc_ = 0.0f;
  282. }
  283. void Network::RegisterRemoteEvent(StringHash eventType)
  284. {
  285. allowedRemoteEvents_.Insert(eventType);
  286. }
  287. void Network::UnregisterRemoteEvent(StringHash eventType)
  288. {
  289. allowedRemoteEvents_.Erase(eventType);
  290. }
  291. void Network::UnregisterAllRemoteEvents()
  292. {
  293. allowedRemoteEvents_.Clear();
  294. }
  295. void Network::SetPackageCacheDir(const String& path)
  296. {
  297. packageCacheDir_ = AddTrailingSlash(path);
  298. }
  299. Connection* Network::GetConnection(kNet::MessageConnection* connection) const
  300. {
  301. Map<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Find(connection);
  302. if (i != clientConnections_.End())
  303. return i->second_;
  304. else if (serverConnection_ && serverConnection_->GetMessageConnection() == connection)
  305. return serverConnection_;
  306. else
  307. return 0;
  308. }
  309. Connection* Network::GetServerConnection() const
  310. {
  311. return serverConnection_;
  312. }
  313. bool Network::IsServerRunning() const
  314. {
  315. return network_->GetServer();
  316. }
  317. bool Network::CheckRemoteEvent(StringHash eventType) const
  318. {
  319. return allowedRemoteEvents_.Empty() || allowedRemoteEvents_.Contains(eventType);
  320. }
  321. void Network::Update(float timeStep)
  322. {
  323. PROFILE(UpdateNetwork);
  324. // Check if periodic update should happen now
  325. updateAcc_ += timeStep;
  326. bool updateNow = updateAcc_ >= updateInterval_;
  327. if (updateNow)
  328. {
  329. // Notify of the impending update to allow for example updated client controls to be set
  330. SendEvent(E_NETWORKUPDATE);
  331. updateAcc_ = fmodf(updateAcc_, updateInterval_);
  332. }
  333. // Process server connection if it exists
  334. if (serverConnection_)
  335. {
  336. kNet::MessageConnection* connection = serverConnection_->GetMessageConnection();
  337. // Check for state transitions
  338. kNet::ConnectionState state = connection->GetConnectionState();
  339. if (serverConnection_->IsConnectPending() && state == kNet::ConnectionOK)
  340. OnServerConnected();
  341. else if (state == kNet::ConnectionPeerClosed)
  342. serverConnection_->Disconnect();
  343. else if (state == kNet::ConnectionClosed)
  344. OnServerDisconnected();
  345. if (serverConnection_)
  346. {
  347. // Receive new messages
  348. connection->Process();
  349. // Process latest data messages waiting for the correct nodes or components to be created
  350. serverConnection_->ProcessPendingLatestData();
  351. // Send the client update
  352. if (updateNow)
  353. {
  354. serverConnection_->SendClientUpdate();
  355. serverConnection_->SendQueuedRemoteEvents();
  356. }
  357. }
  358. }
  359. // Process client connections if the server has been started
  360. kNet::SharedPtr<kNet::NetworkServer> server = network_->GetServer();
  361. if (server)
  362. {
  363. server->Process();
  364. if (updateNow)
  365. {
  366. // Send server updates for each client connection
  367. for (Map<kNet::MessageConnection*, SharedPtr<Connection> >::ConstIterator i = clientConnections_.Begin();
  368. i != clientConnections_.End(); ++i)
  369. {
  370. i->second_->SendServerUpdate();
  371. i->second_->SendQueuedRemoteEvents();
  372. }
  373. }
  374. }
  375. }
  376. void Network::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  377. {
  378. using namespace BeginFrame;
  379. Update(eventData[P_TIMESTEP].GetFloat());
  380. }
  381. void Network::OnServerConnected()
  382. {
  383. serverConnection_->SetConnectPending(false);
  384. LOGINFO("Connected to server");
  385. // Send the identity map now
  386. VectorBuffer msg;
  387. msg.WriteVariantMap(serverConnection_->GetIdentity());
  388. serverConnection_->SendMessage(MSG_IDENTITY, true, true, msg);
  389. SendEvent(E_SERVERCONNECTED);
  390. }
  391. void Network::OnServerDisconnected()
  392. {
  393. // Differentiate between failed connection, and disconnection
  394. bool failedConnect = serverConnection_ && serverConnection_->IsConnectPending();
  395. if (!failedConnect)
  396. {
  397. LOGINFO("Disconnected from server");
  398. SendEvent(E_SERVERDISCONNECTED);
  399. }
  400. else
  401. {
  402. LOGERROR("Failed to connect to server");
  403. SendEvent(E_CONNECTFAILED);
  404. }
  405. serverConnection_.Reset();
  406. }