Network.h 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. //
  2. // Copyright (c) 2008-2020 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #pragma once
  23. #include "../Container/HashSet.h"
  24. #include "../Core/Object.h"
  25. #include "../IO/VectorBuffer.h"
  26. #include "../Network/Connection.h"
  27. namespace Urho3D
  28. {
  29. class HttpRequest;
  30. class MemoryBuffer;
  31. class Scene;
  32. /// %Network subsystem. Manages client-server communications using the UDP protocol.
  33. class URHO3D_API Network : public Object
  34. {
  35. URHO3D_OBJECT(Network, Object);
  36. public:
  37. /// Construct.
  38. explicit Network(Context* context);
  39. /// Destruct.
  40. ~Network() override;
  41. /// Handle an inbound message.
  42. void HandleMessage(const SLNet::AddressOrGUID& source, int packetID, int msgID, const char* data, size_t numBytes);
  43. /// Handle a new client connection.
  44. void NewConnectionEstablished(const SLNet::AddressOrGUID& connection);
  45. /// Handle a client disconnection.
  46. void ClientDisconnected(const SLNet::AddressOrGUID& connection);
  47. /// Set the data that will be used for a reply to attempts at host discovery on LAN/subnet.
  48. void SetDiscoveryBeacon(const VariantMap& data);
  49. /// Scan the LAN/subnet for available hosts.
  50. void DiscoverHosts(unsigned port);
  51. /// Set password for the client/server communcation.
  52. void SetPassword(const String& password);
  53. /// Set NAT server information.
  54. void SetNATServerInfo(const String& address, unsigned short port);
  55. /// Connect to a server using UDP protocol. Return true if connection process successfully started.
  56. bool Connect(const String& address, unsigned short port, Scene* scene, const VariantMap& identity = Variant::emptyVariantMap);
  57. /// Disconnect the connection to the server. If wait time is non-zero, will block while waiting for disconnect to finish.
  58. void Disconnect(int waitMSec = 0);
  59. /// Start a server on a port using UDP protocol. Return true if successful.
  60. bool StartServer(unsigned short port, unsigned int maxConnections = 128);
  61. /// Stop the server.
  62. void StopServer();
  63. /// Start NAT punchtrough client to allow remote connections.
  64. void StartNATClient();
  65. /// Get local server GUID.
  66. const String& GetGUID() const { return guid_; }
  67. /// Attempt to connect to NAT server.
  68. void AttemptNATPunchtrough(const String& guid, Scene* scene, const VariantMap& identity = Variant::emptyVariantMap);
  69. /// Broadcast a message with content ID to all client connections.
  70. void BroadcastMessage(int msgID, bool reliable, bool inOrder, const VectorBuffer& msg, unsigned contentID = 0);
  71. /// Broadcast a message with content ID to all client connections.
  72. void BroadcastMessage(int msgID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes, unsigned contentID = 0);
  73. /// Broadcast a remote event to all client connections.
  74. void BroadcastRemoteEvent(StringHash eventType, bool inOrder, const VariantMap& eventData = Variant::emptyVariantMap);
  75. /// Broadcast a remote event to all client connections in a specific scene.
  76. void BroadcastRemoteEvent(Scene* scene, StringHash eventType, bool inOrder, const VariantMap& eventData = Variant::emptyVariantMap);
  77. /// Broadcast a remote event with the specified node as a sender. Is sent to all client connections in the node's scene.
  78. void BroadcastRemoteEvent(Node* node, StringHash eventType, bool inOrder, const VariantMap& eventData = Variant::emptyVariantMap);
  79. /// Set network update FPS.
  80. void SetUpdateFps(int fps);
  81. /// Set simulated latency in milliseconds. This adds a fixed delay before sending each packet.
  82. void SetSimulatedLatency(int ms);
  83. /// Set simulated packet loss probability between 0.0 - 1.0.
  84. void SetSimulatedPacketLoss(float probability);
  85. /// Register a remote event as allowed to be received. There is also a fixed blacklist of events that can not be allowed in any case, such as ConsoleCommand.
  86. void RegisterRemoteEvent(StringHash eventType);
  87. /// Unregister a remote event as allowed to received.
  88. void UnregisterRemoteEvent(StringHash eventType);
  89. /// Unregister all remote events.
  90. void UnregisterAllRemoteEvents();
  91. /// Set the package download cache directory.
  92. void SetPackageCacheDir(const String& path);
  93. /// Trigger all client connections in the specified scene to download a package file from the server. Can be used to download additional resource packages when clients are already joined in the scene. The package must have been added as a requirement to the scene, or else the eventual download will fail.
  94. void SendPackageToClients(Scene* scene, PackageFile* package);
  95. /// Perform an HTTP request to the specified URL. Empty verb defaults to a GET request. Return a request object which can be used to read the response data.
  96. SharedPtr<HttpRequest> MakeHttpRequest(const String& url, const String& verb = String::EMPTY, const Vector<String>& headers = Vector<String>(), const String& postData = String::EMPTY);
  97. /// Ban specific IP addresses.
  98. void BanAddress(const String& address);
  99. /// Return network update FPS.
  100. int GetUpdateFps() const { return updateFps_; }
  101. /// Return simulated latency in milliseconds.
  102. int GetSimulatedLatency() const { return simulatedLatency_; }
  103. /// Return simulated packet loss probability.
  104. float GetSimulatedPacketLoss() const { return simulatedPacketLoss_; }
  105. /// Return a client or server connection by RakNet connection address, or null if none exist.
  106. Connection* GetConnection(const SLNet::AddressOrGUID& connection) const;
  107. /// Return the connection to the server. Null if not connected.
  108. Connection* GetServerConnection() const;
  109. /// Return all client connections.
  110. Vector<SharedPtr<Connection> > GetClientConnections() const;
  111. /// Return whether the server is running.
  112. bool IsServerRunning() const;
  113. /// Return whether a remote event is allowed to be received.
  114. bool CheckRemoteEvent(StringHash eventType) const;
  115. /// Return the package download cache directory.
  116. const String& GetPackageCacheDir() const { return packageCacheDir_; }
  117. /// Process incoming messages from connections. Called by HandleBeginFrame.
  118. void Update(float timeStep);
  119. /// Send outgoing messages after frame logic. Called by HandleRenderUpdate.
  120. void PostUpdate(float timeStep);
  121. private:
  122. /// Handle begin frame event.
  123. void HandleBeginFrame(StringHash eventType, VariantMap& eventData);
  124. /// Handle render update frame event.
  125. void HandleRenderUpdate(StringHash eventType, VariantMap& eventData);
  126. /// Handle server connection.
  127. void OnServerConnected(const SLNet::AddressOrGUID& address);
  128. /// Handle server disconnection.
  129. void OnServerDisconnected(const SLNet::AddressOrGUID& address);
  130. /// Reconfigure network simulator parameters on all existing connections.
  131. void ConfigureNetworkSimulator();
  132. /// All incoming packages are handled here.
  133. void HandleIncomingPacket(SLNet::Packet* packet, bool isServer);
  134. /// SLikeNet peer instance for server connection.
  135. SLNet::RakPeerInterface* rakPeer_;
  136. /// SLikeNet peer instance for client connection.
  137. SLNet::RakPeerInterface* rakPeerClient_;
  138. /// Client's server connection.
  139. SharedPtr<Connection> serverConnection_;
  140. /// Server's client connections.
  141. HashMap<SLNet::AddressOrGUID, SharedPtr<Connection> > clientConnections_;
  142. /// Allowed remote events.
  143. HashSet<StringHash> allowedRemoteEvents_;
  144. /// Remote event fixed blacklist.
  145. HashSet<StringHash> blacklistedRemoteEvents_;
  146. /// Networked scenes.
  147. HashSet<Scene*> networkScenes_;
  148. /// Update FPS.
  149. int updateFps_;
  150. /// Simulated latency (send delay) in milliseconds.
  151. int simulatedLatency_;
  152. /// Simulated packet loss probability between 0.0 - 1.0.
  153. float simulatedPacketLoss_;
  154. /// Update time interval.
  155. float updateInterval_;
  156. /// Update time accumulator.
  157. float updateAcc_;
  158. /// Package cache directory.
  159. String packageCacheDir_;
  160. /// Whether we started as server or not.
  161. bool isServer_;
  162. /// Server/Client password used for connecting.
  163. String password_;
  164. /// Scene which will be used for NAT punchtrough connections.
  165. Scene* scene_;
  166. /// Client identify for NAT punchtrough connections.
  167. VariantMap identity_;
  168. /// NAT punchtrough server information.
  169. SLNet::SystemAddress* natPunchServerAddress_;
  170. /// NAT punchtrough client for the server.
  171. SLNet::NatPunchthroughClient* natPunchthroughServerClient_;
  172. /// NAT punchtrough client for the client.
  173. SLNet::NatPunchthroughClient* natPunchthroughClient_;
  174. /// Remote GUID information.
  175. SLNet::RakNetGUID* remoteGUID_;
  176. /// Local server GUID.
  177. String guid_;
  178. };
  179. /// Register Network library objects.
  180. void URHO3D_API RegisterNetworkLibrary(Context* context);
  181. }