Network.cpp 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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 "Mutex.h"
  28. #include "Network.h"
  29. #include "NetworkEvents.h"
  30. #include "Peer.h"
  31. #include "ProcessUtils.h"
  32. #include "Profiler.h"
  33. #include "StringUtils.h"
  34. #include <enet/enet.h>
  35. #include "DebugNew.h"
  36. static unsigned numInstances = 0;
  37. OBJECTTYPESTATIC(Network);
  38. Network::Network(Context* context) :
  39. Object(context),
  40. serverHost_(0),
  41. clientHost_(0),
  42. serverMaxConnections_(32),
  43. clientMaxConnections_(2),
  44. numChannels_(4),
  45. dataInBps_(0),
  46. dataOutBps_(0)
  47. {
  48. {
  49. MutexLock Lock(GetStaticMutex());
  50. if (!numInstances)
  51. {
  52. if (enet_initialize() != 0)
  53. LOGERROR("Could not initialize networking");
  54. }
  55. ++numInstances;
  56. }
  57. SubscribeToEvent(E_BEGINFRAME, HANDLER(Network, HandleBeginFrame));
  58. }
  59. Network::~Network()
  60. {
  61. StopServer();
  62. StopClient();
  63. {
  64. MutexLock Lock(GetStaticMutex());
  65. --numInstances;
  66. if (!numInstances)
  67. enet_deinitialize();
  68. }
  69. }
  70. void Network::SetServerMaxConnections(unsigned connections)
  71. {
  72. if (!connections)
  73. connections = 1;
  74. serverMaxConnections_ = connections;
  75. }
  76. void Network::SetClientMaxConnections(unsigned connections)
  77. {
  78. if (!connections)
  79. connections = 1;
  80. clientMaxConnections_ = connections;
  81. }
  82. void Network::SetNumChannels(unsigned channels)
  83. {
  84. if (!channels)
  85. channels = 1;
  86. if (channels > 255)
  87. channels = 255;
  88. numChannels_ = channels;
  89. if (serverHost_)
  90. enet_host_channel_limit(serverHost_, numChannels_);
  91. if (clientHost_)
  92. enet_host_channel_limit(clientHost_, numChannels_);
  93. }
  94. void Network::SetDataRate(int dataInBps, int dataOutBps)
  95. {
  96. dataInBps_ = Max(dataInBps, 0);
  97. dataOutBps_ = Max(dataOutBps, 0);
  98. if (serverHost_)
  99. enet_host_bandwidth_limit(serverHost_, dataInBps_, dataOutBps_);
  100. if (clientHost_)
  101. enet_host_bandwidth_limit(clientHost_, dataInBps_, dataOutBps_);
  102. }
  103. void Network::Update()
  104. {
  105. PROFILE(UpdateNetwork);
  106. // Service hosts if they exist
  107. if (serverHost_)
  108. Update(serverHost_);
  109. if (clientHost_)
  110. Update(clientHost_);
  111. // Update peers and purge those that are disconnected
  112. for (Vector<SharedPtr<Peer> >::Iterator i = peers_.Begin(); i != peers_.End();)
  113. {
  114. (*i)->Update();
  115. if ((*i)->GetConnectionState() == CS_DISCONNECTED)
  116. i = peers_.Erase(i);
  117. else
  118. ++i;
  119. }
  120. }
  121. bool Network::StartServer(unsigned short port)
  122. {
  123. StopServer();
  124. ENetAddress server;
  125. server.host = ENET_HOST_ANY;
  126. server.port = port;
  127. serverHost_ = enet_host_create(&server, serverMaxConnections_, numChannels_, dataInBps_, dataOutBps_);
  128. if (serverHost_)
  129. enet_host_compress_with_range_coder(serverHost_);
  130. else
  131. {
  132. LOGERROR("Failed to start server on port " + port);
  133. return false;
  134. }
  135. LOGINFO("Started server on port " + port);
  136. return true;
  137. }
  138. Peer* Network::Connect(const String& address, unsigned short port)
  139. {
  140. // Create client host if one did not exist already
  141. if (!clientHost_)
  142. {
  143. clientHost_ = enet_host_create(0, clientMaxConnections_, numChannels_, dataInBps_, dataOutBps_);
  144. if (clientHost_)
  145. enet_host_compress_with_range_coder(clientHost_);
  146. else
  147. {
  148. LOGERROR("Failed to create client host");
  149. return 0;
  150. }
  151. }
  152. // Attempt to connect
  153. ENetAddress server;
  154. enet_address_set_host(&server, address.CString());
  155. server.port = port;
  156. ENetPeer* enetPeer = enet_host_connect(clientHost_, &server, numChannels_, 0);
  157. if (!enetPeer)
  158. {
  159. LOGERROR("No available network connections");
  160. return 0;
  161. }
  162. // Create a Peer instance for the server
  163. SharedPtr<Peer> newPeer(new Peer(context_, enetPeer, PEER_SERVER));
  164. enetPeer->data = newPeer.GetPtr();
  165. peers_.Push(newPeer);
  166. LOGINFO("Connecting to " + address + ":" + port);
  167. return newPeer;
  168. }
  169. void Network::Broadcast(const void* data, unsigned size, unsigned char channel, bool reliable, bool inOrder)
  170. {
  171. if (!serverHost_)
  172. {
  173. LOGERROR("No server running, can not broadcast");
  174. return;
  175. }
  176. if ((!data) || (!size))
  177. return;
  178. ENetPacket* enetPacket = enet_packet_create(data, size, reliable ? ENET_PACKET_FLAG_RELIABLE : (inOrder ? 0 :
  179. ENET_PACKET_FLAG_UNSEQUENCED));
  180. enet_host_broadcast(serverHost_, channel, enetPacket);
  181. }
  182. void Network::Broadcast(const VectorBuffer& packet, unsigned char channel, bool reliable, bool inOrder)
  183. {
  184. if (!serverHost_)
  185. {
  186. LOGERROR("No server running, can not broadcast");
  187. return;
  188. }
  189. if (!packet.GetSize())
  190. return;
  191. ENetPacket* enetPacket = enet_packet_create(packet.GetData(), packet.GetSize(), reliable ? ENET_PACKET_FLAG_RELIABLE :
  192. (inOrder ? 0 : ENET_PACKET_FLAG_UNSEQUENCED));
  193. enet_host_broadcast(serverHost_, channel, enetPacket);
  194. }
  195. void Network::StopServer()
  196. {
  197. if (serverHost_)
  198. {
  199. // Disconnect all peers created through the server host
  200. for (Vector<SharedPtr<Peer> >::Iterator i = peers_.Begin(); i != peers_.End(); ++i)
  201. {
  202. if ((*i)->GetPeerType() == PEER_CLIENT)
  203. (*i)->Disconnect();
  204. }
  205. // Update once more, so that disconnect packet (maybe) goes to clients
  206. Update(serverHost_);
  207. // Then perform forcible disconnection
  208. for (Vector<SharedPtr<Peer> >::Iterator i = peers_.Begin(); i != peers_.End(); ++i)
  209. {
  210. if ((*i)->GetPeerType() == PEER_CLIENT)
  211. (*i)->OnDisconnect();
  212. }
  213. enet_host_destroy(serverHost_);
  214. serverHost_ = 0;
  215. LOGINFO("Stopped server");
  216. }
  217. }
  218. void Network::StopClient()
  219. {
  220. if (clientHost_)
  221. {
  222. // Disconnect all peers created through the client host
  223. for (Vector<SharedPtr<Peer> >::Iterator i = peers_.Begin(); i != peers_.End(); ++i)
  224. {
  225. if ((*i)->GetPeerType() == PEER_SERVER)
  226. (*i)->Disconnect();
  227. }
  228. // Update once more, so that disconnect packet (maybe) goes to server
  229. Update(clientHost_);
  230. // Then perform forcible disconnection
  231. for (Vector<SharedPtr<Peer> >::Iterator i = peers_.Begin(); i != peers_.End(); ++i)
  232. {
  233. if ((*i)->GetPeerType() == PEER_SERVER)
  234. (*i)->OnDisconnect();
  235. }
  236. enet_host_destroy(clientHost_);
  237. clientHost_ = 0;
  238. LOGINFO("Stopped client");
  239. }
  240. }
  241. Peer* Network::GetPeer(unsigned index) const
  242. {
  243. return index < peers_.Size() ? peers_[index] : (Peer*)0;
  244. }
  245. Peer* Network::GetServerPeer() const
  246. {
  247. // Just return the first server peer
  248. for (Vector<SharedPtr<Peer> >::ConstIterator i = peers_.Begin(); i != peers_.End(); ++i)
  249. {
  250. if ((*i)->GetPeerType() == PEER_SERVER)
  251. return *i;
  252. }
  253. return 0;
  254. }
  255. void Network::Update(ENetHost* enetHost)
  256. {
  257. ENetEvent enetEvent;
  258. ENetPeer* enetPeer;
  259. Peer* peer;
  260. while (enet_host_service(enetHost, &enetEvent, 0) > 0)
  261. {
  262. enetPeer = enetEvent.peer;
  263. peer = static_cast<Peer*>(enetPeer->data);
  264. switch (enetEvent.type)
  265. {
  266. case ENET_EVENT_TYPE_CONNECT:
  267. if (!peer)
  268. {
  269. // If no existing Peer instance (server operation), create one now
  270. SharedPtr<Peer> newPeer(new Peer(context_, enetPeer, PEER_CLIENT));
  271. enetPeer->data = newPeer.GetPtr();
  272. peers_.Push(newPeer);
  273. newPeer->OnConnect();
  274. }
  275. else
  276. peer->OnConnect();
  277. break;
  278. case ENET_EVENT_TYPE_RECEIVE:
  279. if (peer)
  280. {
  281. // queue the packet
  282. QueuedPacket newPacket;
  283. newPacket.packet_ = enetEvent.packet;
  284. newPacket.channel_ = enetEvent.channelID;
  285. peer->packets_[enetEvent.channelID].Push(newPacket);
  286. }
  287. else
  288. enet_packet_destroy(enetEvent.packet);
  289. break;
  290. case ENET_EVENT_TYPE_DISCONNECT:
  291. if (peer)
  292. {
  293. peer->OnDisconnect();
  294. enetPeer->data = 0;
  295. }
  296. break;
  297. }
  298. }
  299. }
  300. void Network::HandleBeginFrame(StringHash eventType, VariantMap& eventData)
  301. {
  302. Update();
  303. }