Network.h 6.5 KB

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