Network.cpp 10.0 KB

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