Network.h 6.6 KB

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