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
33#if defined(NETWORK_ENABLE_TEST_INJECTION)
34namespace kcenon::network::tests::support
35{
36 class ws_server_probe;
37} // namespace kcenon::network::tests::support
38#endif
39
41{
42 class ws_session_manager;
43
52 {
53 uint16_t port = 8080;
54 std::string path = "/";
55 size_t max_connections = 1000;
56 std::chrono::milliseconds ping_interval{30000};
57 bool auto_pong = true;
58 size_t max_message_size = 10 * 1024 * 1024;
59 };
60
77 {
78 public:
79 // Allow server to create connections
80 friend class messaging_ws_server;
81
82 // Constructor - used by server
83 explicit ws_connection(std::shared_ptr<class ws_connection_impl> impl);
84
86 ~ws_connection() override = default;
87
88 // ========================================================================
89 // i_websocket_session interface implementation
90 // ========================================================================
91
98 [[nodiscard]] auto id() const -> std::string_view override;
99
106 [[nodiscard]] auto is_connected() const -> bool override;
107
115 [[nodiscard]] auto send(std::vector<uint8_t>&& data) -> VoidResult override;
116
122 auto close() -> void override;
123
131 [[nodiscard]] auto send_text(std::string&& message) -> VoidResult override;
132
140 [[nodiscard]] auto send_binary(std::vector<uint8_t>&& data) -> VoidResult override;
141
149 auto close(uint16_t code, std::string_view reason = "") -> void override;
150
157 [[nodiscard]] auto path() const -> std::string_view override;
158
163 auto remote_endpoint() const -> std::string;
164
165 private:
167 auto get_impl() const -> std::shared_ptr<ws_connection_impl> { return pimpl_; }
168
169 std::shared_ptr<ws_connection_impl> pimpl_;
170 };
171
173 class ws_connection_impl;
174
216 : public std::enable_shared_from_this<messaging_ws_server>
218 {
219 public:
221 using connection_callback_t = std::function<void(std::shared_ptr<ws_connection>)>;
223 using disconnection_callback_t = std::function<void(const std::string&, internal::ws_close_code, const std::string&)>;
225 using message_callback_t = std::function<void(std::shared_ptr<ws_connection>, const internal::ws_message&)>;
227 using text_message_callback_t = std::function<void(std::shared_ptr<ws_connection>, const std::string&)>;
229 using binary_message_callback_t = std::function<void(std::shared_ptr<ws_connection>, const std::vector<uint8_t>&)>;
231 using error_callback_t = std::function<void(const std::string&, std::error_code)>;
232
237 explicit messaging_ws_server(std::string_view server_id);
238
243 ~messaging_ws_server() noexcept override;
244
245 // Non-copyable, non-movable
247 messaging_ws_server& operator=(const messaging_ws_server&) = delete;
250
251 // ========================================================================
252 // Lifecycle Management
253 // ========================================================================
254
260 [[nodiscard]] auto start_server(const ws_server_config& config) -> VoidResult;
261
268 [[nodiscard]] auto start_server(uint16_t port, std::string_view path = "/") -> VoidResult;
269
274 [[nodiscard]] auto stop_server() -> VoidResult;
275
280 [[nodiscard]] auto server_id() const -> const std::string&;
281
286 auto broadcast_text(const std::string& message) -> void;
287
292 auto broadcast_binary(const std::vector<uint8_t>& data) -> void;
293
299 auto get_connection(const std::string& connection_id) -> std::shared_ptr<ws_connection>;
300
305 auto get_all_connections() -> std::vector<std::string>;
306
307 // ========================================================================
308 // i_network_component interface implementation
309 // ========================================================================
310
317 [[nodiscard]] auto is_running() const -> bool override;
318
324 auto wait_for_stop() -> void override;
325
326 // ========================================================================
327 // i_websocket_server interface implementation
328 // ========================================================================
329
337 [[nodiscard]] auto start(uint16_t port) -> VoidResult override;
338
345 [[nodiscard]] auto stop() -> VoidResult override;
346
353 [[nodiscard]] auto connection_count() const -> size_t override;
354
361 auto set_connection_callback(interfaces::i_websocket_server::connection_callback_t callback) -> void override;
362
369 auto set_disconnection_callback(interfaces::i_websocket_server::disconnection_callback_t callback) -> void override;
370
377 auto set_text_callback(interfaces::i_websocket_server::text_callback_t callback) -> void override;
378
385 auto set_binary_callback(interfaces::i_websocket_server::binary_callback_t callback) -> void override;
386
393 auto set_error_callback(interfaces::i_websocket_server::error_callback_t callback) -> void override;
394
395 private:
396#if defined(NETWORK_ENABLE_TEST_INJECTION)
397 // Test-only: grants tests/support/ws_server_probe access to private
398 // surfaces without leaking them through the public API.
399 friend class kcenon::network::tests::support::ws_server_probe;
400#endif
401
402 // =====================================================================
403 // Internal Implementation Methods
404 // =====================================================================
405
412 auto do_start_impl(uint16_t port, std::string_view path) -> VoidResult;
413
418 auto do_stop_impl() -> VoidResult;
419
423 auto do_accept() -> void;
424
428 auto handle_new_connection(std::shared_ptr<asio::ip::tcp::socket> socket) -> void;
429
433 auto on_message(std::shared_ptr<ws_connection> conn, const internal::ws_message& msg) -> void;
434
438 auto on_close(const std::string& conn_id, internal::ws_close_code code, const std::string& reason) -> void;
439
443 auto on_error(const std::string& conn_id, std::error_code ec) -> void;
444
445 // =====================================================================
446 // Internal Callback Helpers
447 // =====================================================================
448
453 auto invoke_connection_callback(std::shared_ptr<ws_connection> conn) -> void;
454
461 auto invoke_disconnection_callback(const std::string& conn_id,
463 const std::string& reason) -> void;
464
470 auto invoke_message_callback(std::shared_ptr<ws_connection> conn,
471 const internal::ws_message& msg) -> void;
472
478 auto invoke_error_callback(const std::string& conn_id, std::error_code ec) -> void;
479
482
491 >;
492
493 // =====================================================================
494 // Member Variables
495 // =====================================================================
496
497 std::string server_id_;
503 std::unique_ptr<asio::io_context> io_context_;
504 std::unique_ptr<asio::executor_work_guard<asio::io_context::executor_type>> work_guard_;
505 std::unique_ptr<asio::ip::tcp::acceptor> acceptor_;
506 mutable std::mutex acceptor_mutex_;
508 std::shared_ptr<integration::thread_pool_interface> thread_pool_;
509 std::future<void> io_context_future_;
511 std::shared_ptr<ws_session_manager> session_mgr_;
512 };
513
514// =====================================================================
515// Unified Pattern Type Aliases
516// =====================================================================
517// These aliases provide a consistent API pattern across all protocols,
518// making WebSocket servers accessible via the unified template naming.
519// See: unified_messaging_server.h for TCP, unified_udp_messaging_server.h for UDP.
520
533
549
550} // 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.
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.
Thread-safe lifecycle state management for network components.
uint32_t code
Definition hpack.cpp:668
Component lifecycle management (start, stop, restart).
ws_close_code
WebSocket close status codes (RFC 6455 Section 7.4).
Result< std::monostate > VoidResult
ws_server_callback
Callback indices for messaging_ws_server.
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.