Network.h 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. //
  2. // Copyright (c) 2008-2015 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. #include <kNet/IMessageHandler.h>
  28. #include <kNet/INetworkServerListener.h>
  29. namespace Atomic
  30. {
  31. class HttpRequest;
  32. class MemoryBuffer;
  33. class Scene;
  34. /// MessageConnection hash function.
  35. template <class T> unsigned MakeHash(kNet::MessageConnection* value)
  36. {
  37. return ((unsigned)(size_t)value) >> 9;
  38. }
  39. /// %Network subsystem. Manages client-server communications using the UDP protocol.
  40. class ATOMIC_API Network : public Object, public kNet::IMessageHandler, public kNet::INetworkServerListener
  41. {
  42. friend class MasterServerClient;
  43. OBJECT(Network);
  44. public:
  45. /// Construct.
  46. Network(Context* context);
  47. /// Destruct.
  48. ~Network();
  49. /// Handle a kNet message from either a client or the server.
  50. virtual void HandleMessage
  51. (kNet::MessageConnection* source, kNet::packet_id_t packetId, kNet::message_id_t msgId, const char* data, size_t numBytes);
  52. /// Compute the content ID for a message.
  53. virtual u32 ComputeContentID(kNet::message_id_t msgId, const char* data, size_t numBytes);
  54. /// Handle a new client connection.
  55. virtual void NewConnectionEstablished(kNet::MessageConnection* connection);
  56. /// Handle a client disconnection.
  57. virtual void ClientDisconnected(kNet::MessageConnection* connection);
  58. /// Connect to a server using UDP protocol. Return true if connection process successfully started.
  59. bool Connect(const String& address, unsigned short port, Scene* scene, const VariantMap& identity = Variant::emptyVariantMap);
  60. /// Connect to a server, reusing an existing Socket
  61. bool ConnectWithExistingSocket(kNet::Socket* existingSocket, Scene* scene);
  62. /// Disconnect the connection to the server. If wait time is non-zero, will block while waiting for disconnect to finish.
  63. void Disconnect(int waitMSec = 0);
  64. /// Start a server on a port using UDP protocol. Return true if successful.
  65. bool StartServer(unsigned short port);
  66. /// Stop the server.
  67. void StopServer();
  68. /// Broadcast a message with content ID to all client connections.
  69. void BroadcastMessage(int msgID, bool reliable, bool inOrder, const VectorBuffer& msg, unsigned contentID = 0);
  70. /// Broadcast a message with content ID to all client connections.
  71. void BroadcastMessage
  72. (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
  77. (Scene* scene, StringHash eventType, bool inOrder, const VariantMap& eventData = Variant::emptyVariantMap);
  78. /// Broadcast a remote event with the specified node as a sender. Is sent to all client connections in the node's scene.
  79. void BroadcastRemoteEvent
  80. (Node* node, StringHash eventType, bool inOrder, const VariantMap& eventData = Variant::emptyVariantMap);
  81. /// Set network update FPS.
  82. void SetUpdateFps(int fps);
  83. /// Set simulated latency in milliseconds. This adds a fixed delay before sending each packet.
  84. void SetSimulatedLatency(int ms);
  85. /// Set simulated packet loss probability between 0.0 - 1.0.
  86. void SetSimulatedPacketLoss(float probability);
  87. /// 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.
  88. void RegisterRemoteEvent(StringHash eventType);
  89. /// Unregister a remote event as allowed to received.
  90. void UnregisterRemoteEvent(StringHash eventType);
  91. /// Unregister all remote events.
  92. void UnregisterAllRemoteEvents();
  93. /// Set the package download cache directory.
  94. void SetPackageCacheDir(const String& path);
  95. /// 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.
  96. void SendPackageToClients(Scene* scene, PackageFile* package);
  97. /// 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.
  98. SharedPtr<HttpRequest> MakeHttpRequest
  99. (const String& url, const String& verb = String::EMPTY, const Vector<String>& headers = Vector<String>(),
  100. const String& postData = String::EMPTY);
  101. /// Return network update FPS.
  102. int GetUpdateFps() const { return updateFps_; }
  103. /// Return simulated latency in milliseconds.
  104. int GetSimulatedLatency() const { return simulatedLatency_; }
  105. /// Return simulated packet loss probability.
  106. float GetSimulatedPacketLoss() const { return simulatedPacketLoss_; }
  107. /// Return a client or server connection by kNet MessageConnection, or null if none exist.
  108. Connection* GetConnection(kNet::MessageConnection* connection) const;
  109. // Return the connection with the matching endpoint
  110. bool IsEndPointConnected(const kNet::EndPoint& endPoint) const;
  111. /// Return the connection to the server. Null if not connected.
  112. Connection* GetServerConnection() const;
  113. /// Return all client connections.
  114. Vector<SharedPtr<Connection> > GetClientConnections() const;
  115. /// Return whether the server is running.
  116. bool IsServerRunning() const;
  117. /// Return whether a remote event is allowed to be received.
  118. bool CheckRemoteEvent(StringHash eventType) const;
  119. /// Return the package download cache directory.
  120. const String& GetPackageCacheDir() const { return packageCacheDir_; }
  121. /// Process incoming messages from connections. Called by HandleBeginFrame.
  122. void Update(float timeStep);
  123. /// Send outgoing messages after frame logic. Called by HandleRenderUpdate.
  124. void PostUpdate(float timeStep);
  125. unsigned short GetServerPort() const { return serverPort_; }
  126. private:
  127. /// Handle begin frame event.
  128. void HandleBeginFrame(StringHash eventType, VariantMap& eventData);
  129. /// Handle render update frame event.
  130. void HandleRenderUpdate(StringHash eventType, VariantMap& eventData);
  131. /// Handle server connection.
  132. void OnServerConnected();
  133. /// Handle server disconnection.
  134. void OnServerDisconnected();
  135. /// Reconfigure network simulator parameters on all existing connections.
  136. void ConfigureNetworkSimulator();
  137. void HandleClientConnected(StringHash eventType, VariantMap& eventData);
  138. kNet::Network* GetKnetNetwork() { return network_; }
  139. /// kNet instance.
  140. kNet::Network* network_;
  141. /// Client's server connection.
  142. SharedPtr<Connection> serverConnection_;
  143. /// Server's client connections.
  144. HashMap<kNet::MessageConnection*, SharedPtr<Connection> > clientConnections_;
  145. /// Allowed remote events.
  146. HashSet<StringHash> allowedRemoteEvents_;
  147. /// Remote event fixed blacklist.
  148. HashSet<StringHash> blacklistedRemoteEvents_;
  149. /// Networked scenes.
  150. HashSet<Scene*> networkScenes_;
  151. /// Update FPS.
  152. int updateFps_;
  153. /// Simulated latency (send delay) in milliseconds.
  154. int simulatedLatency_;
  155. /// Simulated packet loss probability between 0.0 - 1.0.
  156. float simulatedPacketLoss_;
  157. /// Update time interval.
  158. float updateInterval_;
  159. /// Update time accumulator.
  160. float updateAcc_;
  161. /// Package cache directory.
  162. String packageCacheDir_;
  163. unsigned short serverPort_;
  164. };
  165. /// Register Network library objects.
  166. void ATOMIC_API RegisterNetworkLibrary(Context* context);
  167. }