Network System 0.1.1
High-performance modular networking library for scalable client-server applications
Loading...
Searching...
No Matches
websocket_server.h
Go to the documentation of this file.
1// BSD 3-Clause License
2// Copyright (c) 2024, 🍀☀🌕🌥 🌊
3// See the LICENSE file in the project root for full license information.
4
5#pragma once
6
14
15#include <chrono>
16#include <cstdint>
17#include <functional>
18#include <future>
19#include <memory>
20#include <mutex>
21#include <string>
22#include <string_view>
23#include <system_error>
24#include <vector>
25
26#include <asio.hpp>
27
29{
30 class websocket_socket;
31}
32
34{
35 class ws_session_manager;
36
45 {
46 uint16_t port = 8080;
47 std::string path = "/";
48 size_t max_connections = 1000;
49 std::chrono::milliseconds ping_interval{30000};
50 bool auto_pong = true;
51 size_t max_message_size = 10 * 1024 * 1024;
52 };
53
70 {
71 public:
72 // Allow server to create connections
73 friend class messaging_ws_server;
74
75 // Constructor - used by server
76 explicit ws_connection(std::shared_ptr<class ws_connection_impl> impl);
77
79 ~ws_connection() override = default;
80
81 // ========================================================================
82 // i_websocket_session interface implementation
83 // ========================================================================
84
91 [[nodiscard]] auto id() const -> std::string_view override;
92
99 [[nodiscard]] auto is_connected() const -> bool override;
100
108 [[nodiscard]] auto send(std::vector<uint8_t>&& data) -> VoidResult override;
109
115 auto close() -> void override;
116
124 [[nodiscard]] auto send_text(std::string&& message) -> VoidResult override;
125
133 [[nodiscard]] auto send_binary(std::vector<uint8_t>&& data) -> VoidResult override;
134
142 auto close(uint16_t code, std::string_view reason = "") -> void override;
143
150 [[nodiscard]] auto path() const -> std::string_view override;
151
156 auto remote_endpoint() const -> std::string;
157
158 private:
160 auto get_impl() const -> std::shared_ptr<ws_connection_impl> { return pimpl_; }
161
162 std::shared_ptr<ws_connection_impl> pimpl_;
163 };
164
166 class ws_connection_impl;
167
209 : public std::enable_shared_from_this<messaging_ws_server>
211 {
212 public:
214 using connection_callback_t = std::function<void(std::shared_ptr<ws_connection>)>;
216 using disconnection_callback_t = std::function<void(const std::string&, internal::ws_close_code, const std::string&)>;
218 using message_callback_t = std::function<void(std::shared_ptr<ws_connection>, const internal::ws_message&)>;
220 using text_message_callback_t = std::function<void(std::shared_ptr<ws_connection>, const std::string&)>;
222 using binary_message_callback_t = std::function<void(std::shared_ptr<ws_connection>, const std::vector<uint8_t>&)>;
224 using error_callback_t = std::function<void(const std::string&, std::error_code)>;
225
230 explicit messaging_ws_server(std::string_view server_id);
231
236 ~messaging_ws_server() noexcept override;
237
238 // Non-copyable, non-movable
240 messaging_ws_server& operator=(const messaging_ws_server&) = delete;
243
244 // ========================================================================
245 // Lifecycle Management
246 // ========================================================================
247
253 [[nodiscard]] auto start_server(const ws_server_config& config) -> VoidResult;
254
261 [[nodiscard]] auto start_server(uint16_t port, std::string_view path = "/") -> VoidResult;
262
267 [[nodiscard]] auto stop_server() -> VoidResult;
268
273 [[nodiscard]] auto server_id() const -> const std::string&;
274
279 auto broadcast_text(const std::string& message) -> void;
280
285 auto broadcast_binary(const std::vector<uint8_t>& data) -> void;
286
292 auto get_connection(const std::string& connection_id) -> std::shared_ptr<ws_connection>;
293
298 auto get_all_connections() -> std::vector<std::string>;
299
300 // ========================================================================
301 // i_network_component interface implementation
302 // ========================================================================
303
310 [[nodiscard]] auto is_running() const -> bool override;
311
317 auto wait_for_stop() -> void override;
318
319 // ========================================================================
320 // i_websocket_server interface implementation
321 // ========================================================================
322
330 [[nodiscard]] auto start(uint16_t port) -> VoidResult override;
331
338 [[nodiscard]] auto stop() -> VoidResult override;
339
346 [[nodiscard]] auto connection_count() const -> size_t override;
347
354 auto set_connection_callback(interfaces::i_websocket_server::connection_callback_t callback) -> void override;
355
362 auto set_disconnection_callback(interfaces::i_websocket_server::disconnection_callback_t callback) -> void override;
363
370 auto set_text_callback(interfaces::i_websocket_server::text_callback_t callback) -> void override;
371
378 auto set_binary_callback(interfaces::i_websocket_server::binary_callback_t callback) -> void override;
379
386 auto set_error_callback(interfaces::i_websocket_server::error_callback_t callback) -> void override;
387
388 private:
389 // =====================================================================
390 // Internal Implementation Methods
391 // =====================================================================
392
399 auto do_start_impl(uint16_t port, std::string_view path) -> VoidResult;
400
405 auto do_stop_impl() -> VoidResult;
406
410 auto do_accept() -> void;
411
415 auto handle_new_connection(std::shared_ptr<asio::ip::tcp::socket> socket) -> void;
416
420 auto on_message(std::shared_ptr<ws_connection> conn, const internal::ws_message& msg) -> void;
421
425 auto on_close(const std::string& conn_id, internal::ws_close_code code, const std::string& reason) -> void;
426
430 auto on_error(const std::string& conn_id, std::error_code ec) -> void;
431
432 // =====================================================================
433 // Internal Callback Helpers
434 // =====================================================================
435
440 auto invoke_connection_callback(std::shared_ptr<ws_connection> conn) -> void;
441
448 auto invoke_disconnection_callback(const std::string& conn_id,
449 internal::ws_close_code code,
450 const std::string& reason) -> void;
451
457 auto invoke_message_callback(std::shared_ptr<ws_connection> conn,
458 const internal::ws_message& msg) -> void;
459
465 auto invoke_error_callback(const std::string& conn_id, std::error_code ec) -> void;
466
469
471 using callbacks_t = utils::callback_manager<
478 >;
479
480 // =====================================================================
481 // Member Variables
482 // =====================================================================
483
484 std::string server_id_;
485 utils::lifecycle_manager lifecycle_;
490 std::unique_ptr<asio::io_context> io_context_;
491 std::unique_ptr<asio::executor_work_guard<asio::io_context::executor_type>> work_guard_;
492 std::unique_ptr<asio::ip::tcp::acceptor> acceptor_;
493 mutable std::mutex acceptor_mutex_;
495 std::shared_ptr<integration::thread_pool_interface> thread_pool_;
496 std::future<void> io_context_future_;
499 };
500
501// =====================================================================
502// Unified Pattern Type Aliases
503// =====================================================================
504// These aliases provide a consistent API pattern across all protocols,
505// making WebSocket servers accessible via the unified template naming.
506// See: unified_messaging_server.h for TCP, unified_udp_messaging_server.h for UDP.
507
520
536
537} // namespace kcenon::network::core
Thread-safe callback registration and invocation manager.
High-level WebSocket server with connection management.
auto do_accept() -> void
Starts accepting new connections.
auto set_binary_callback(interfaces::i_websocket_server::binary_callback_t callback) -> void override
Sets the callback for binary messages (interface version).
std::function< void(std::shared_ptr< ws_connection >)> connection_callback_t
Callback type for new connections.
~messaging_ws_server() noexcept override
Destructor. Automatically stops the server if still running.
auto broadcast_binary(const std::vector< uint8_t > &data) -> void
Broadcasts a binary message to all connected clients.
std::shared_ptr< ws_session_manager > session_mgr_
std::function< void(const std::string &, std::error_code)> error_callback_t
Callback type for errors.
std::unique_ptr< asio::io_context > io_context_
auto set_disconnection_callback(interfaces::i_websocket_server::disconnection_callback_t callback) -> void override
Sets the callback for disconnections (interface version).
auto get_all_connections() -> std::vector< std::string >
Gets all connection IDs.
auto set_connection_callback(interfaces::i_websocket_server::connection_callback_t callback) -> void override
Sets the callback for new connections (interface version).
auto handle_new_connection(std::shared_ptr< asio::ip::tcp::socket > socket) -> void
Handles a new connection.
auto do_stop_impl() -> VoidResult
WebSocket-specific implementation of server stop.
auto wait_for_stop() -> void override
Blocks until stop() is called.
auto invoke_message_callback(std::shared_ptr< ws_connection > conn, const internal::ws_message &msg) -> void
Invokes the message callback.
auto invoke_error_callback(const std::string &conn_id, std::error_code ec) -> void
Invokes the error callback.
auto is_running() const -> bool override
Checks if the server is currently running.
auto set_error_callback(interfaces::i_websocket_server::error_callback_t callback) -> void override
Sets the callback for errors (interface version).
auto invoke_connection_callback(std::shared_ptr< ws_connection > conn) -> void
Invokes the connection callback.
auto stop_server() -> VoidResult
Stops the server and releases all resources.
auto do_start_impl(uint16_t port, std::string_view path) -> VoidResult
WebSocket-specific implementation of server start.
auto start(uint16_t port) -> VoidResult override
Starts the WebSocket server on the specified port.
auto start_server(const ws_server_config &config) -> VoidResult
Starts the server with full configuration.
auto connection_count() const -> size_t override
Gets the number of active WebSocket connections.
auto on_error(const std::string &conn_id, std::error_code ec) -> void
Handles errors.
auto server_id() const -> const std::string &
Returns the server identifier.
auto on_message(std::shared_ptr< ws_connection > conn, const internal::ws_message &msg) -> void
Handles received WebSocket messages.
std::function< void(std::shared_ptr< ws_connection >, const std::string &)> text_message_callback_t
Callback type for text messages.
auto invoke_disconnection_callback(const std::string &conn_id, internal::ws_close_code code, const std::string &reason) -> void
Invokes the disconnection callback.
messaging_ws_server(std::string_view server_id)
Constructs a WebSocket server.
auto set_text_callback(interfaces::i_websocket_server::text_callback_t callback) -> void override
Sets the callback for text messages (interface version).
std::unique_ptr< asio::ip::tcp::acceptor > acceptor_
std::function< void(std::shared_ptr< ws_connection >, const std::vector< uint8_t > &)> binary_message_callback_t
Callback type for binary messages.
std::shared_ptr< integration::thread_pool_interface > thread_pool_
std::unique_ptr< asio::executor_work_guard< asio::io_context::executor_type > > work_guard_
auto get_connection(const std::string &connection_id) -> std::shared_ptr< ws_connection >
Gets a connection by ID.
auto broadcast_text(const std::string &message) -> void
Broadcasts a text message to all connected clients.
std::function< void(const std::string &, internal::ws_close_code, const std::string &)> disconnection_callback_t
Callback type for disconnections.
auto on_close(const std::string &conn_id, internal::ws_close_code code, const std::string &reason) -> void
Handles connection close.
std::function< void(std::shared_ptr< ws_connection >, const internal::ws_message &)> message_callback_t
Callback type for WebSocket messages.
auto stop() -> VoidResult override
Stops the WebSocket server.
Represents a WebSocket connection to a client.
auto is_connected() const -> bool override
Checks if the session is currently connected.
std::shared_ptr< ws_connection_impl > pimpl_
ws_connection(std::shared_ptr< class ws_connection_impl > impl)
auto send_text(std::string &&message) -> VoidResult override
Sends a text message to the client.
auto send_binary(std::vector< uint8_t > &&data) -> VoidResult override
Sends a binary message to the client.
auto path() const -> std::string_view override
Gets the requested path from the handshake.
auto close() -> void override
Closes the session.
auto id() const -> std::string_view override
Gets the unique identifier for this session.
auto send(std::vector< uint8_t > &&data) -> VoidResult override
Sends data to the client.
auto remote_endpoint() const -> std::string
Gets the remote endpoint address.
auto get_impl() const -> std::shared_ptr< ws_connection_impl >
Internal: Get the implementation pointer (for server use)
~ws_connection() override=default
Destructor.
Thread-safe WebSocket session lifecycle management.
Interface for WebSocket server components.
std::function< void(std::string_view, const std::vector< uint8_t > &)> binary_callback_t
Callback type for binary messages (session_id, data)
std::function< void(std::string_view, const std::string &)> text_callback_t
Callback type for text messages (session_id, message)
Interface for a WebSocket session on the server side.
Component lifecycle management (start, stop, restart).
ws_close_code
WebSocket close status codes (RFC 6455 Section 7.4).
ws_server_callback
Callback indices for messaging_ws_server.
std::mutex mutex
Network-specific error and result type definitions.
Configuration for WebSocket server.
std::chrono::milliseconds ping_interval
Ping interval.
size_t max_connections
Max concurrent connections.
size_t max_message_size
Max message size (10MB)
Represents a complete WebSocket message.
Thread system integration interface for network_system.