Network.cpp 14 KB

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