Network.h 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. // Copyright (c) 2008-2023 the Urho3D project
  2. // License: MIT
  3. #pragma once
  4. #include "../Container/HashSet.h"
  5. #include "../Core/Object.h"
  6. #include "../IO/VectorBuffer.h"
  7. #include "../Network/Connection.h"
  8. namespace Urho3D
  9. {
  10. class HttpRequest;
  11. class MemoryBuffer;
  12. class Scene;
  13. /// %Network subsystem. Manages client-server communications using the UDP protocol.
  14. class URHO3D_API Network : public Object
  15. {
  16. URHO3D_OBJECT(Network, Object);
  17. public:
  18. /// Construct.
  19. explicit Network(Context* context);
  20. /// Destruct.
  21. ~Network() override;
  22. /// Handle an inbound message.
  23. void HandleMessage(const SLNet::AddressOrGUID& source, int packetID, int msgID, const char* data, size_t numBytes);
  24. /// Handle a new client connection.
  25. void NewConnectionEstablished(const SLNet::AddressOrGUID& connection);
  26. /// Handle a client disconnection.
  27. void ClientDisconnected(const SLNet::AddressOrGUID& connection);
  28. /// Set the data that will be used for a reply to attempts at host discovery on LAN/subnet.
  29. void SetDiscoveryBeacon(const VariantMap& data);
  30. /// Scan the LAN/subnet for available hosts.
  31. void DiscoverHosts(unsigned port);
  32. /// Set password for the client/server communcation.
  33. void SetPassword(const String& password);
  34. /// Set NAT server information.
  35. void SetNATServerInfo(const String& address, unsigned short port);
  36. /// Connect to a server using UDP protocol. Return true if connection process successfully started.
  37. bool Connect(const String& address, unsigned short port, Scene* scene, const VariantMap& identity = Variant::emptyVariantMap);
  38. /// Disconnect the connection to the server. If wait time is non-zero, will block while waiting for disconnect to finish.
  39. void Disconnect(int waitMSec = 0);
  40. /// Start a server on a port using UDP protocol. Return true if successful.
  41. bool StartServer(unsigned short port, unsigned int maxConnections = 128);
  42. /// Stop the server.
  43. void StopServer();
  44. /// Start NAT punchtrough client to allow remote connections.
  45. void StartNATClient();
  46. /// Get local server GUID.
  47. /// @property{get_guid}
  48. const String& GetGUID() const { return guid_; }
  49. /// Attempt to connect to NAT server.
  50. void AttemptNATPunchtrough(const String& guid, Scene* scene, const VariantMap& identity = Variant::emptyVariantMap);
  51. /// Broadcast a message with content ID to all client connections.
  52. void BroadcastMessage(int msgID, bool reliable, bool inOrder, const VectorBuffer& msg, unsigned contentID = 0);
  53. /// Broadcast a message with content ID to all client connections.
  54. void BroadcastMessage(int msgID, bool reliable, bool inOrder, const byte* data, unsigned numBytes, unsigned contentID = 0);
  55. /// Broadcast a remote event to all client connections.
  56. void BroadcastRemoteEvent(StringHash eventType, bool inOrder, const VariantMap& eventData = Variant::emptyVariantMap);
  57. /// Broadcast a remote event to all client connections in a specific scene.
  58. void BroadcastRemoteEvent(Scene* scene, StringHash eventType, bool inOrder, const VariantMap& eventData = Variant::emptyVariantMap);
  59. /// Broadcast a remote event with the specified node as a sender. Is sent to all client connections in the node's scene.
  60. void BroadcastRemoteEvent(Node* node, StringHash eventType, bool inOrder, const VariantMap& eventData = Variant::emptyVariantMap);
  61. /// Set network update FPS.
  62. /// @property
  63. void SetUpdateFps(int fps);
  64. /// Set simulated latency in milliseconds. This adds a fixed delay before sending each packet.
  65. /// @property
  66. void SetSimulatedLatency(int ms);
  67. /// Set simulated packet loss probability between 0.0 - 1.0.
  68. /// @property
  69. void SetSimulatedPacketLoss(float probability);
  70. /// 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.
  71. void RegisterRemoteEvent(StringHash eventType);
  72. /// Unregister a remote event as allowed to received.
  73. void UnregisterRemoteEvent(StringHash eventType);
  74. /// Unregister all remote events.
  75. void UnregisterAllRemoteEvents();
  76. /// Set the package download cache directory.
  77. /// @property
  78. void SetPackageCacheDir(const String& path);
  79. /// 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.
  80. void SendPackageToClients(Scene* scene, PackageFile* package);
  81. /// 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.
  82. SharedPtr<HttpRequest> MakeHttpRequest(const String& url, const String& verb = String::EMPTY, const Vector<String>& headers = Vector<String>(), const String& postData = String::EMPTY);
  83. /// Ban specific IP addresses.
  84. void BanAddress(const String& address);
  85. /// Return network update FPS.
  86. /// @property
  87. int GetUpdateFps() const { return updateFps_; }
  88. /// Return simulated latency in milliseconds.
  89. /// @property
  90. int GetSimulatedLatency() const { return simulatedLatency_; }
  91. /// Return simulated packet loss probability.
  92. /// @property
  93. float GetSimulatedPacketLoss() const { return simulatedPacketLoss_; }
  94. /// Return a client or server connection by RakNet connection address, or null if none exist.
  95. Connection* GetConnection(const SLNet::AddressOrGUID& connection) const;
  96. /// Return the connection to the server. Null if not connected.
  97. /// @property
  98. Connection* GetServerConnection() const;
  99. /// Return all client connections.
  100. /// @property
  101. Vector<SharedPtr<Connection>> GetClientConnections() const;
  102. /// Return whether the server is running.
  103. /// @property
  104. bool IsServerRunning() const;
  105. /// Return whether a remote event is allowed to be received.
  106. bool CheckRemoteEvent(StringHash eventType) const;
  107. /// Return the package download cache directory.
  108. /// @property
  109. const String& GetPackageCacheDir() const { return packageCacheDir_; }
  110. /// Process incoming messages from connections. Called by HandleBeginFrame.
  111. void Update(float timeStep);
  112. /// Send outgoing messages after frame logic. Called by HandleRenderUpdate.
  113. void PostUpdate(float timeStep);
  114. private:
  115. /// Handle begin frame event.
  116. void HandleBeginFrame(StringHash eventType, VariantMap& eventData);
  117. /// Handle render update frame event.
  118. void HandleRenderUpdate(StringHash eventType, VariantMap& eventData);
  119. /// Handle server connection.
  120. void OnServerConnected(const SLNet::AddressOrGUID& address);
  121. /// Handle server disconnection.
  122. void OnServerDisconnected(const SLNet::AddressOrGUID& address);
  123. /// Reconfigure network simulator parameters on all existing connections.
  124. void ConfigureNetworkSimulator();
  125. /// All incoming packages are handled here.
  126. void HandleIncomingPacket(SLNet::Packet* packet, bool isServer);
  127. /// SLikeNet peer instance for server connection.
  128. SLNet::RakPeerInterface* rakPeer_;
  129. /// SLikeNet peer instance for client connection.
  130. SLNet::RakPeerInterface* rakPeerClient_;
  131. /// Client's server connection.
  132. SharedPtr<Connection> serverConnection_;
  133. /// Server's client connections.
  134. HashMap<SLNet::AddressOrGUID, SharedPtr<Connection>> clientConnections_;
  135. /// Allowed remote events.
  136. HashSet<StringHash> allowedRemoteEvents_;
  137. /// Remote event fixed blacklist.
  138. HashSet<StringHash> blacklistedRemoteEvents_;
  139. /// Networked scenes.
  140. HashSet<Scene*> networkScenes_;
  141. /// Update FPS.
  142. int updateFps_;
  143. /// Simulated latency (send delay) in milliseconds.
  144. int simulatedLatency_;
  145. /// Simulated packet loss probability between 0.0 - 1.0.
  146. float simulatedPacketLoss_;
  147. /// Update time interval.
  148. float updateInterval_;
  149. /// Update time accumulator.
  150. float updateAcc_;
  151. /// Package cache directory.
  152. String packageCacheDir_;
  153. /// Whether we started as server or not.
  154. bool isServer_;
  155. /// Server/Client password used for connecting.
  156. String password_;
  157. /// Scene which will be used for NAT punchtrough connections.
  158. Scene* scene_;
  159. /// Client identify for NAT punchtrough connections.
  160. VariantMap identity_;
  161. /// NAT punchtrough server information.
  162. SLNet::SystemAddress* natPunchServerAddress_;
  163. /// NAT punchtrough client for the server.
  164. SLNet::NatPunchthroughClient* natPunchthroughServerClient_;
  165. /// NAT punchtrough client for the client.
  166. SLNet::NatPunchthroughClient* natPunchthroughClient_;
  167. /// Remote GUID information.
  168. SLNet::RakNetGUID* remoteGUID_;
  169. /// Local server GUID.
  170. String guid_;
  171. };
  172. /// Register Network library objects.
  173. /// @nobind
  174. void URHO3D_API RegisterNetworkLibrary(Context* context);
  175. }