Network.h 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. //
  2. // Copyright (c) 2008-2014 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 "Connection.h"
  24. #include "HashSet.h"
  25. #include "Object.h"
  26. #include "VectorBuffer.h"
  27. #include <kNet/IMessageHandler.h>
  28. #include <kNet/INetworkServerListener.h>
  29. namespace Urho3D
  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 URHO3D_API Network : public Object, public kNet::IMessageHandler, public kNet::INetworkServerListener
  41. {
  42. OBJECT(Network);
  43. public:
  44. /// Construct.
  45. Network(Context* context);
  46. /// Destruct.
  47. ~Network();
  48. /// Handle a kNet message from either a client or the server.
  49. virtual void HandleMessage(kNet::MessageConnection *source, kNet::packet_id_t packetId, kNet::message_id_t msgId, const char *data, size_t numBytes);
  50. /// Compute the content ID for a message.
  51. virtual u32 ComputeContentID(kNet::message_id_t msgId, const char *data, size_t numBytes);
  52. /// Handle a new client connection.
  53. virtual void NewConnectionEstablished(kNet::MessageConnection* connection);
  54. /// Handle a client disconnection.
  55. virtual void ClientDisconnected(kNet::MessageConnection* connection);
  56. /// Connect to a server using UDP protocol. Return true if connection process successfully started.
  57. bool Connect(const String& address, unsigned short port, Scene* scene, const VariantMap& identity = Variant::emptyVariantMap);
  58. /// Disconnect the connection to the server. If wait time is non-zero, will block while waiting for disconnect to finish.
  59. void Disconnect(int waitMSec = 0);
  60. /// Start a server on a port using UDP protocol. Return true if successful.
  61. bool StartServer(unsigned short port);
  62. /// Stop the server.
  63. void StopServer();
  64. /// Broadcast a message with content ID to all client connections.
  65. void BroadcastMessage(int msgID, bool reliable, bool inOrder, const VectorBuffer& msg, unsigned contentID = 0);
  66. /// Broadcast a message with content ID to all client connections.
  67. void BroadcastMessage(int msgID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes, unsigned contentID = 0);
  68. /// Broadcast a remote event to all client connections.
  69. void BroadcastRemoteEvent(StringHash eventType, bool inOrder, const VariantMap& eventData = Variant::emptyVariantMap);
  70. /// Broadcast a remote event to all client connections in a specific scene.
  71. void BroadcastRemoteEvent(Scene* scene, StringHash eventType, bool inOrder, const VariantMap& eventData = Variant::emptyVariantMap);
  72. /// Broadcast a remote event with the specified node as a sender. Is sent to all client connections in the node's scene.
  73. void BroadcastRemoteEvent(Node* node, StringHash eventType, bool inOrder, const VariantMap& eventData = Variant::emptyVariantMap);
  74. /// Set network update FPS.
  75. void SetUpdateFps(int fps);
  76. /// 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.
  77. void RegisterRemoteEvent(StringHash eventType);
  78. /// Unregister a remote event as allowed to received.
  79. void UnregisterRemoteEvent(StringHash eventType);
  80. /// Unregister all remote events.
  81. void UnregisterAllRemoteEvents();
  82. /// Set the package download cache directory.
  83. void SetPackageCacheDir(const String& path);
  84. /// 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.
  85. void SendPackageToClients(Scene* scene, PackageFile* package);
  86. /// 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.
  87. SharedPtr<HttpRequest> MakeHttpRequest(const String& url, const String& verb = String::EMPTY, const Vector<String>& headers = Vector<String>(), const String& postData = String::EMPTY);
  88. /// Return network update FPS.
  89. int GetUpdateFps() const { return updateFps_; }
  90. /// Return a client or server connection by kNet MessageConnection, or null if none exist.
  91. Connection* GetConnection(kNet::MessageConnection* connection) const;
  92. /// Return the connection to the server. Null if not connected.
  93. Connection* GetServerConnection() const;
  94. /// Return all client connections.
  95. Vector<SharedPtr<Connection> > GetClientConnections() const;
  96. /// Return whether the server is running.
  97. bool IsServerRunning() const;
  98. /// Return whether a remote event is allowed to be received.
  99. bool CheckRemoteEvent(StringHash eventType) const;
  100. /// Return the package download cache directory.
  101. const String& GetPackageCacheDir() const { return packageCacheDir_; }
  102. /// Process incoming messages from connections. Called by HandleBeginFrame.
  103. void Update(float timeStep);
  104. /// Send outgoing messages after frame logic. Called by HandleRenderUpdate.
  105. void PostUpdate(float timeStep);
  106. private:
  107. /// Handle begin frame event.
  108. void HandleBeginFrame(StringHash eventType, VariantMap& eventData);
  109. /// Handle render update frame event.
  110. void HandleRenderUpdate(StringHash eventType, VariantMap& eventData);
  111. /// Handle server connection.
  112. void OnServerConnected();
  113. /// Handle server disconnection.
  114. void OnServerDisconnected();
  115. /// kNet instance.
  116. kNet::Network* network_;
  117. /// Client's server connection.
  118. SharedPtr<Connection> serverConnection_;
  119. /// Server's client connections.
  120. HashMap<kNet::MessageConnection*, SharedPtr<Connection> > clientConnections_;
  121. /// Allowed remote events.
  122. HashSet<StringHash> allowedRemoteEvents_;
  123. /// Remote event fixed blacklist.
  124. HashSet<StringHash> blacklistedRemoteEvents_;
  125. /// Networked scenes.
  126. HashSet<Scene*> networkScenes_;
  127. /// Update FPS.
  128. int updateFps_;
  129. /// Update time interval.
  130. float updateInterval_;
  131. /// Update time accumulator.
  132. float updateAcc_;
  133. /// Package cache directory.
  134. String packageCacheDir_;
  135. };
  136. /// Register Network library objects.
  137. void URHO3D_API RegisterNetworkLibrary(Context* context);
  138. }