Network System 0.1.1
High-performance modular networking library for scalable client-server applications
Loading...
Searching...
No Matches
websocket_client.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
7#include <chrono>
8#include <cstdint>
9#include <functional>
10#include <future>
11#include <map>
12#include <memory>
13#include <mutex>
14#include <string>
15#include <string_view>
16#include <system_error>
17#include <vector>
18
19#include <asio.hpp>
20
28
30{
31 class tcp_socket;
32 class websocket_socket;
33}
34
36{
45 {
46 std::string host;
47 uint16_t port = 80;
48 std::string path = "/";
49 std::map<std::string, std::string> headers;
50 std::chrono::milliseconds connect_timeout{10000};
51 std::chrono::milliseconds ping_interval{30000};
52 bool auto_pong = true;
53 bool auto_reconnect = false;
54 size_t max_message_size = 10 * 1024 * 1024;
55 };
56
97 : public std::enable_shared_from_this<messaging_ws_client>
99 {
100 public:
102 using message_callback_t = std::function<void(const internal::ws_message&)>;
104 using text_message_callback_t = std::function<void(const std::string&)>;
106 using binary_message_callback_t = std::function<void(const std::vector<uint8_t>&)>;
108 using connected_callback_t = std::function<void()>;
110 using disconnected_callback_t = std::function<void(internal::ws_close_code, const std::string&)>;
112 using error_callback_t = std::function<void(std::error_code)>;
113
118 explicit messaging_ws_client(std::string_view client_id);
119
124 ~messaging_ws_client() noexcept override;
125
126 // Non-copyable, non-movable
128 messaging_ws_client& operator=(const messaging_ws_client&) = delete;
131
132 // ========================================================================
133 // Lifecycle Management
134 // ========================================================================
135
141 [[nodiscard]] auto start_client(const ws_client_config& config) -> VoidResult;
142
150 [[nodiscard]] auto start_client(std::string_view host, uint16_t port,
151 std::string_view path = "/") -> VoidResult;
152
157 [[nodiscard]] auto stop_client() -> VoidResult;
158
163 [[nodiscard]] auto client_id() const -> const std::string&;
164
170 [[nodiscard]] auto send_ping(std::vector<uint8_t>&& payload = {}) -> VoidResult;
171
172 // ========================================================================
173 // i_network_component interface implementation
174 // ========================================================================
175
182 [[nodiscard]] auto is_running() const -> bool override;
183
189 auto wait_for_stop() -> void override;
190
191 // ========================================================================
192 // i_websocket_client interface implementation
193 // ========================================================================
194
204 [[nodiscard]] auto start(
205 std::string_view host,
206 uint16_t port,
207 std::string_view path = "/") -> VoidResult override;
208
215 [[nodiscard]] auto stop() -> VoidResult override;
216
223 [[nodiscard]] auto is_connected() const -> bool override;
224
233 [[nodiscard]] auto send_text(
234 std::string&& message,
235 interfaces::i_websocket_client::send_callback_t handler = nullptr) -> VoidResult override;
236
245 [[nodiscard]] auto send_binary(
246 std::vector<uint8_t>&& data,
247 interfaces::i_websocket_client::send_callback_t handler = nullptr) -> VoidResult override;
248
256 [[nodiscard]] auto ping(std::vector<uint8_t>&& payload = {}) -> VoidResult override;
257
266 [[nodiscard]] auto close(
267 uint16_t code = 1000,
268 std::string_view reason = "") -> VoidResult override;
269
277
285
293
301
309
310 private:
311 // =====================================================================
312 // Internal Implementation Methods
313 // =====================================================================
314
322 auto do_start_impl(std::string_view host, uint16_t port, std::string_view path) -> VoidResult;
323
328 auto do_stop_impl() -> VoidResult;
329
333 auto do_connect() -> void;
334
338 auto on_message(const internal::ws_message& msg) -> void;
339
343 auto on_ping(const std::vector<uint8_t>& payload) -> void;
344
348 auto on_close(internal::ws_close_code code, const std::string& reason) -> void;
349
353 auto on_error(std::error_code ec) -> void;
354
355 // =====================================================================
356 // Internal Callback Helpers
357 // =====================================================================
358
363 auto invoke_message_callback(const internal::ws_message& msg) -> void;
364
368 auto invoke_connected_callback() -> void;
369
376 const std::string& reason) -> void;
377
382 auto invoke_error_callback(std::error_code ec) -> void;
383
386
395 >;
396
397 // =====================================================================
398 // Member Variables
399 // =====================================================================
400
401 std::string client_id_;
404 std::atomic<bool> is_connected_{false};
408 std::unique_ptr<asio::io_context> io_context_;
409 std::unique_ptr<asio::executor_work_guard<asio::io_context::executor_type>> work_guard_;
411 std::shared_ptr<integration::thread_pool_interface> thread_pool_;
412 std::future<void> io_context_future_;
414 std::shared_ptr<internal::websocket_socket> ws_socket_;
415 std::mutex ws_socket_mutex_;
416 };
417
418// =====================================================================
419// Unified Pattern Type Aliases
420// =====================================================================
421// These aliases provide a consistent API pattern across all protocols,
422// making WebSocket clients accessible via the unified template naming.
423// See: unified_messaging_client.h for TCP, unified_udp_messaging_client.h for UDP.
424
437
453
454} // namespace kcenon::network::core
Thread-safe callback registration and invocation manager.
High-level WebSocket client with automatic connection management.
auto start(std::string_view host, uint16_t port, std::string_view path="/") -> VoidResult override
Starts the WebSocket client connecting to the specified endpoint.
auto set_text_callback(interfaces::i_websocket_client::text_callback_t callback) -> void override
Sets the callback for text messages (interface version).
auto do_start_impl(std::string_view host, uint16_t port, std::string_view path) -> VoidResult
WebSocket-specific implementation of client start.
auto is_running() const -> bool override
Checks if the client is currently running.
auto ping(std::vector< uint8_t > &&payload={}) -> VoidResult override
Sends a ping frame (interface version).
messaging_ws_client(std::string_view client_id)
Constructs a WebSocket client.
auto stop_client() -> VoidResult
Stops the client and releases all resources.
auto on_error(std::error_code ec) -> void
Handles errors.
std::function< void()> connected_callback_t
Callback type for connection established.
auto do_connect() -> void
Initiates async connection to the server.
auto set_connected_callback(interfaces::i_websocket_client::connected_callback_t callback) -> void override
Sets the callback for connection established (interface version).
auto on_message(const internal::ws_message &msg) -> void
Handles received WebSocket messages.
auto stop() -> VoidResult override
Stops the WebSocket client.
auto on_close(internal::ws_close_code code, const std::string &reason) -> void
Handles connection close.
auto wait_for_stop() -> void override
Blocks until stop() is called.
auto invoke_error_callback(std::error_code ec) -> void
Invokes the error callback.
auto invoke_message_callback(const internal::ws_message &msg) -> void
Invokes the message callback.
~messaging_ws_client() noexcept override
Destructor. Automatically stops the client if still running.
std::function< void(internal::ws_close_code, const std::string &)> disconnected_callback_t
Callback type for disconnection with close code.
std::function< void(const std::string &)> text_message_callback_t
Callback type for text messages.
auto set_binary_callback(interfaces::i_websocket_client::binary_callback_t callback) -> void override
Sets the callback for binary messages (interface version).
auto send_text(std::string &&message, interfaces::i_websocket_client::send_callback_t handler=nullptr) -> VoidResult override
Sends a text message (interface version).
auto invoke_connected_callback() -> void
Invokes the connected callback.
std::shared_ptr< integration::thread_pool_interface > thread_pool_
auto is_connected() const -> bool override
Checks if the WebSocket connection is established.
auto set_disconnected_callback(interfaces::i_websocket_client::disconnected_callback_t callback) -> void override
Sets the callback for disconnection (interface version).
std::function< void(const internal::ws_message &)> message_callback_t
Callback type for WebSocket messages.
auto start_client(const ws_client_config &config) -> VoidResult
Starts the client with full configuration.
auto set_error_callback(interfaces::i_websocket_client::error_callback_t callback) -> void override
Sets the callback for errors (interface version).
auto close(uint16_t code=1000, std::string_view reason="") -> VoidResult override
Closes the WebSocket connection gracefully (interface version).
auto on_ping(const std::vector< uint8_t > &payload) -> void
Handles ping frames.
auto do_stop_impl() -> VoidResult
WebSocket-specific implementation of client stop.
auto send_binary(std::vector< uint8_t > &&data, interfaces::i_websocket_client::send_callback_t handler=nullptr) -> VoidResult override
Sends a binary message (interface version).
auto invoke_disconnected_callback(internal::ws_close_code code, const std::string &reason) -> void
Invokes the disconnected callback.
std::function< void(std::error_code)> error_callback_t
Callback type for errors.
auto client_id() const -> const std::string &
Returns the client identifier.
std::shared_ptr< internal::websocket_socket > ws_socket_
std::unique_ptr< asio::executor_work_guard< asio::io_context::executor_type > > work_guard_
auto send_ping(std::vector< uint8_t > &&payload={}) -> VoidResult
Sends a ping frame.
std::function< void(const std::vector< uint8_t > &)> binary_message_callback_t
Callback type for binary messages.
std::unique_ptr< asio::io_context > io_context_
Interface for WebSocket client components.
std::function< void(std::error_code, std::size_t)> send_callback_t
Callback type for send completion.
std::function< void()> connected_callback_t
Callback type for connection established.
std::function< void(const std::vector< uint8_t > &)> binary_callback_t
Callback type for binary messages.
std::function< void(const std::string &)> text_callback_t
Callback type for text messages.
std::function< void(std::error_code)> error_callback_t
Callback type for errors.
std::function< void(uint16_t code, std::string_view reason)> disconnected_callback_t
Callback type for disconnection (with close code and reason)
Thread-safe lifecycle state management for network components.
Component lifecycle management (start, stop, restart).
ws_close_code
WebSocket close status codes (RFC 6455 Section 7.4).
Result< std::monostate > VoidResult
ws_client_callback
Callback indices for messaging_ws_client.
Network-specific error and result type definitions.
Configuration for WebSocket client.
std::chrono::milliseconds connect_timeout
Connection timeout.
std::string host
Server hostname or IP.
std::chrono::milliseconds ping_interval
Ping interval.
bool auto_reconnect
Auto-reconnect on disconnect.
std::map< std::string, std::string > headers
Additional HTTP headers.
size_t max_message_size
Max message size (10MB)
Represents a complete WebSocket message.
Thread system integration interface for network_system.