Network.h 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Oorni
  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. #pragma once
  24. #include "Connection.h"
  25. #include "HashSet.h"
  26. #include "Object.h"
  27. #include "VectorBuffer.h"
  28. #include <kNet/IMessageHandler.h>
  29. #include <kNet/INetworkServerListener.h>
  30. namespace kNet
  31. {
  32. class MessageConnection;
  33. }
  34. namespace Urho3D
  35. {
  36. class MemoryBuffer;
  37. class Scene;
  38. /// MessageConnection hash function.
  39. template <class T> unsigned MakeHash(kNet::MessageConnection* value)
  40. {
  41. return ((unsigned)value) >> 9;
  42. }
  43. /// %Network subsystem. Manages client-server communications using the UDP protocol.
  44. class Network : public Object, public kNet::IMessageHandler, public kNet::INetworkServerListener
  45. {
  46. OBJECT(Network);
  47. public:
  48. /// Construct.
  49. Network(Context* context);
  50. /// Destruct.
  51. ~Network();
  52. /// Handle a kNet message from either a client or the server.
  53. virtual void HandleMessage(kNet::MessageConnection *source, kNet::packet_id_t packetId, kNet::message_id_t msgId, const char *data, size_t numBytes);
  54. /// Compute the content ID for a message.
  55. virtual u32 ComputeContentID(kNet::message_id_t msgId, const char *data, size_t numBytes);
  56. /// Handle a new client connection.
  57. virtual void NewConnectionEstablished(kNet::MessageConnection* connection);
  58. /// Handle a client disconnection.
  59. virtual void ClientDisconnected(kNet::MessageConnection* connection);
  60. /// Connect to a server using UDP protocol. Return true if connection process successfully started.
  61. bool Connect(const String& address, unsigned short port, Scene* scene, const VariantMap& identity = VariantMap());
  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(int msgID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes, unsigned contentID = 0);
  72. /// Broadcast a remote event to all client connections.
  73. void BroadcastRemoteEvent(StringHash eventType, bool inOrder, const VariantMap& eventData = VariantMap());
  74. /// Broadcast a remote event to all client connections in a specific scene.
  75. void BroadcastRemoteEvent(Scene* scene, StringHash eventType, bool inOrder, const VariantMap& eventData = VariantMap());
  76. /// Broadcast a remote event with the specified node as a sender. Is sent to all client connections in the node's scene.
  77. void BroadcastRemoteEvent(Node* node, StringHash eventType, bool inOrder, const VariantMap& eventData = VariantMap());
  78. /// Set network update FPS.
  79. void SetUpdateFps(int fps);
  80. /// Register a remote event as allowed to be sent and received. If no events are registered, all are allowed.
  81. void RegisterRemoteEvent(StringHash eventType);
  82. /// Unregister a remote event as allowed to be sent and received.
  83. void UnregisterRemoteEvent(StringHash eventType);
  84. /// Unregister all remote events. This results in all being allowed.
  85. void UnregisterAllRemoteEvents();
  86. /// Set the package download cache directory.
  87. void SetPackageCacheDir(const String& path);
  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 sent and received. If no events are registered, all are allowed.
  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. /// Networked scenes.
  124. HashSet<Scene*> networkScenes_;
  125. /// Update FPS.
  126. int updateFps_;
  127. /// Update time interval.
  128. float updateInterval_;
  129. /// Update time accumulator.
  130. float updateAcc_;
  131. /// Package cache directory.
  132. String packageCacheDir_;
  133. };
  134. /// Register Network library objects.
  135. void RegisterNetworkLibrary(Context* context);
  136. }