Kurlyk
Loading...
Searching...
No Matches
WebSocketClient.hpp
Go to the documentation of this file.
1#pragma once
2#ifndef _KURLYK_WEBSOCKET_CLIENT_HPP_INCLUDED
3#define _KURLYK_WEBSOCKET_CLIENT_HPP_INCLUDED
4
7
8namespace kurlyk {
9
13 public:
14
23
27 WebSocketClient(std::unique_ptr<WebSocketConfig> config, std::function<void(bool)> callback = nullptr) {
30 m_client->notify_handler() = []() {
32 };
33 m_client->set_config(std::move(config), std::move(callback));
34 }
35
48 const std::string& url,
49 const Headers& headers = Headers(),
50 const std::string& proxy_server = std::string(),
51 const std::string& proxy_auth = std::string(),
53 long request_timeout = 20,
54 bool reconnect = true,
55 bool verify_cert = true,
56 const std::string& ca_file = std::string(),
57 int rpm = 200) {
60 m_client->notify_handler() = []() {
62 };
64
65 m_config->url = url;
66 m_config->headers = headers;
67 m_config->proxy_server = proxy_server;
68 m_config->proxy_auth = proxy_auth;
69 m_config->proxy_type = proxy_type;
70 m_config->request_timeout = request_timeout;
71 m_config->reconnect = reconnect;
72 m_config->verify_cert = verify_cert;
73 m_config->ca_file = ca_file;
74 m_config->add_rate_limit(rpm, 60000);
75 }
76
79
81 virtual ~WebSocketClient() {
82 auto client = m_client;
84 client->shutdown();
85 });
86 }
87
90 void on_event(std::function<void(std::unique_ptr<WebSocketEventData>)> callback) {
91 m_client->event_handler() = std::move(callback);
92 }
93
96 std::function<void(std::unique_ptr<WebSocketEventData>)>& event_handler() {
97 return m_client->event_handler();
98 }
99
103 std::future<bool> set_config(std::unique_ptr<WebSocketConfig> config) {
104 auto promise = std::make_shared<std::promise<bool>>();
105 auto future = promise->get_future();
106 m_client->set_config(std::move(config), [promise](bool success) {
107 promise->set_value(success);
108 });
110 return future;
111 }
112
116 void set_config(std::unique_ptr<WebSocketConfig> config, std::function<void(bool)> callback) {
117 m_client->set_config(std::move(config), std::move(callback));
119 }
120
123 std::future<bool> connect() {
124 if (m_config) {
125# if __cplusplus >= 201402L
126 auto config = std::make_unique<WebSocketConfig>(*m_config.get());
127# else
128 auto config = std::unique_ptr<WebSocketConfig>(new WebSocketConfig(*m_config.get()));
129# endif
130 m_client->set_config(std::move(config), nullptr);
131 }
132 auto promise = std::make_shared<std::promise<bool>>();
133 auto future = promise->get_future();
134 m_client->connect([promise](bool success) {
135 promise->set_value(success);
136 });
138 return future;
139 }
140
143 void connect(std::function<void(bool)> callback) {
144 if (m_config) {
145# if __cplusplus >= 201402L
146 auto config = std::make_unique<WebSocketConfig>(*m_config.get());
147# else
148 auto config = std::unique_ptr<WebSocketConfig>(new WebSocketConfig(*m_config.get()));
149# endif
150 m_client->set_config(std::move(config), nullptr);
151 }
152 m_client->connect(std::move(callback));
154 }
155
159 auto connect_future = connect();
160 return connect_future.get();
161 }
162
165 std::future<bool> disconnect() {
166 auto promise = std::make_shared<std::promise<bool>>();
167 auto future = promise->get_future();
168 m_client->disconnect([promise](bool success) {
169 promise->set_value(success);
170 });
172 return future;
173 }
174
178 auto disconnect_future = disconnect();
179 return disconnect_future.get();
180 }
181
184 void disconnect(std::function<void(bool success)> callback) {
185 m_client->disconnect(std::move(callback));
187 }
188
191 const bool is_connected() const {
192 return m_client->is_connected();
193 }
194
201 const std::string &message,
202 long rate_limit_id = 0,
203 std::function<void(const std::error_code&)> callback = nullptr) {
204 return m_client->send_message(message, rate_limit_id, std::move(callback));
205 }
206
213 const int status = 1000,
214 const std::string &reason = std::string(),
215 std::function<void(const std::error_code&)> callback = nullptr) {
216 return m_client->send_close(status, reason, std::move(callback));
217 }
218
221 std::list<std::unique_ptr<WebSocketEventData>> receive_events() {
222 return m_client->receive_events();
223 }
224
227 std::unique_ptr<WebSocketEventData> receive_event() {
228 return m_client->receive_event();
229 }
230
233 std::string get_http_version() const {
234 return m_client->get_http_version();
235 }
236
240 return m_client->get_headers();
241 }
242
245 std::string get_remote_endpoint() const {
246 return m_client->get_remote_endpoint();
247 }
248
253 void set_url(const std::string& host, const std::string& path, const std::string& query = "") {
254 init_config();
255 return m_config->set_url(host, path, query);
256 }
257
261 void set_url(const std::string& url, const QueryParams& query) {
262 init_config();
263 return m_config->set_url(url, query);
264 }
265
271 void set_accept_encoding(bool identity = false, bool deflate = false, bool gzip = false, bool brotli = false) {
272 init_config();
273 return m_config->set_accept_encoding(identity, deflate, gzip, brotli);
274 }
275
281 const std::string& ip,
282 int port,
284 init_config();
285 return m_config->set_proxy(ip, port, type);
286 }
287
295 const std::string& ip,
296 int port,
297 const std::string& username,
298 const std::string& password,
300 init_config();
301 return m_config->set_proxy(ip, port, username, password, type);
302 }
303
306 void set_proxy_server(const std::string& server) {
307 init_config();
308 return m_config->set_proxy_server(server);
309 }
310
313 void set_proxy_auth(const std::string& auth) {
314 init_config();
315 return m_config->set_proxy_auth(auth);
316 }
317
321 init_config();
322 return m_config->set_proxy_type(type);
323 }
324
328 void set_proxy_auth(const std::string& username, const std::string& password) {
329 init_config();
330 return m_config->set_proxy_auth(username, password);
331 }
332
337 void set_reconnect(bool reconnect, long reconnect_attempts = 0, long reconnect_delay = 0) {
338 init_config();
339 return m_config->set_reconnect(reconnect, reconnect_attempts, reconnect_delay);
340 }
341
344 void set_user_agent(const std::string& user_agent) {
345 init_config();
346 return m_config->set_user_agent(user_agent);
347 }
348
351 void set_accept_language(const std::string& accept_language) {
352 init_config();
353 return m_config->set_accept_language(accept_language);
354 }
355
358 void set_cookie(const std::string& cookie) {
359 init_config();
360 return m_config->set_cookie(cookie);
361 }
362
365 void set_idle_timeout(long idle_timeout) {
366 init_config();
367 return m_config->set_idle_timeout(idle_timeout);
368 }
369
372 void set_request_timeout(long request_timeout) {
373 init_config();
374 return m_config->set_request_timeout(request_timeout);
375 }
376
379 void set_ca_file(const std::string& ca_file) {
380 init_config();
381 return m_config->set_ca_file(ca_file);
382 }
383
387 void set_ca_file(bool verify_cert, const std::string& ca_file) {
388 init_config();
389 return m_config->set_ca_file(verify_cert, ca_file);
390 }
391
394 void set_verify_cert(bool verify_cert) {
395 init_config();
396 return m_config->set_verify_cert(verify_cert);
397 }
398
408 long add_rate_limit(long requests_per_period, long period_ms) {
409 init_config();
410 return m_config->add_rate_limit(requests_per_period, period_ms);
411 }
412
416 long add_rate_limit_rpm(long requests_per_minute) {
417 long period_ms = 60000; // 1 minute in milliseconds
418 return add_rate_limit(requests_per_minute, period_ms);
419 }
420
424 long add_rate_limit_rps(long requests_per_second) {
425 long period_ms = 1000; // 1 second in milliseconds
426 return add_rate_limit(requests_per_second, period_ms);
427 }
428
429 private:
430 std::shared_ptr<IWebSocketClient> m_client;
431 std::unique_ptr<WebSocketConfig> m_config;
432
434 void init_config() {
435 if (!m_config) {
436# if __cplusplus >= 201402L
437 m_config = std::make_unique<WebSocketConfig>();
438# else
439 m_config = std::unique_ptr<WebSocketConfig>(new WebSocketConfig());
440# endif
441 }
442 }
443
446 static void ensure_initialized() {
447 static bool is_initialized = false;
448 if (!is_initialized) {
449 is_initialized = true;
453 }
454 }
455
456 }; // WebSocketClient
457
458} // namespace kurlyk
459
460#endif // _KURLYK_WEBSOCKET_CLIENT_HPP_INCLUDED
static HttpRequestManager & get_instance()
Get the singleton instance of HttpRequestManager.
std::function< void(std::unique_ptr< WebSocketEventData >)> & event_handler()
Accessor for the event handler function.
std::list< std::unique_ptr< WebSocketEventData > > receive_events()
Retrieves all pending WebSocket events in a batch.
void set_proxy_type(ProxyType type)
Sets the proxy type.
void set_proxy_auth(const std::string &username, const std::string &password)
Configures proxy authentication credentials.
static void ensure_initialized()
Ensures the WebSocket and network components are initialized.
void set_accept_language(const std::string &accept_language)
Sets the Accept-Language header.
void set_verify_cert(bool verify_cert)
Sets whether to verify the server’s certificate.
void set_cookie(const std::string &cookie)
Sets the cookie data.
void set_proxy(const std::string &ip, int port, ProxyType type=ProxyType::PROXY_HTTP)
Sets the proxy server address.
void on_event(std::function< void(std::unique_ptr< WebSocketEventData >)> callback)
Sets a callback for WebSocket events.
std::string get_http_version() const
Retrieves the HTTP version used in the WebSocket connection.
void set_user_agent(const std::string &user_agent)
Sets the User-Agent header.
void set_idle_timeout(long idle_timeout)
Configures the idle timeout for the WebSocket connection.
std::unique_ptr< WebSocketEventData > receive_event()
Retrieves a single WebSocket event, if available.
WebSocketClient(const std::string &url, const Headers &headers=Headers(), const std::string &proxy_server=std::string(), const std::string &proxy_auth=std::string(), ProxyType proxy_type=ProxyType::PROXY_HTTP, long request_timeout=20, bool reconnect=true, bool verify_cert=true, const std::string &ca_file=std::string(), int rpm=200)
Constructor with URL for configuration.
void set_url(const std::string &url, const QueryParams &query)
Sets the WebSocket server URL with specified query parameters.
void set_proxy_auth(const std::string &auth)
Sets the proxy authentication credentials.
WebSocketClient & operator=(const WebSocketClient &)=delete
const bool is_connected() const
Checks if the WebSocket is connected.
std::unique_ptr< WebSocketConfig > m_config
WebSocket configuration object.
void set_accept_encoding(bool identity=false, bool deflate=false, bool gzip=false, bool brotli=false)
Sets the Accept-Encoding header with specified encodings.
bool send_close(const int status=1000, const std::string &reason=std::string(), std::function< void(const std::error_code &)> callback=nullptr)
Sends a close request to the WebSocket server.
bool disconnect_and_wait()
Disconnects from the WebSocket server, blocking until the disconnection completes.
void set_reconnect(bool reconnect, long reconnect_attempts=0, long reconnect_delay=0)
Configures reconnection behavior.
std::string get_remote_endpoint() const
Retrieves the remote endpoint information.
void init_config()
Initializes the WebSocket configuration if it is not already set.
long add_rate_limit(long requests_per_period, long period_ms)
Adds a rate limit configuration to control the frequency of WebSocket messages.
void disconnect(std::function< void(bool success)> callback)
Disconnects from the WebSocket server and invokes a callback upon completion.
void set_ca_file(bool verify_cert, const std::string &ca_file)
Sets certificate verification and sets the CA certificate file.
void set_ca_file(const std::string &ca_file)
Sets the path to the CA certificate file.
long add_rate_limit_rpm(long requests_per_minute)
Adds a rate limit based on Requests Per Minute (RPM).
WebSocketClient(const WebSocketClient &)=delete
void set_proxy_server(const std::string &server)
Sets the proxy server address.
long add_rate_limit_rps(long requests_per_second)
Adds a rate limit based on Requests Per Second (RPS).
WebSocketClient(std::unique_ptr< WebSocketConfig > config, std::function< void(bool)> callback=nullptr)
Constructor with configuration.
void set_config(std::unique_ptr< WebSocketConfig > config, std::function< void(bool)> callback)
Sets the WebSocket configuration and executes a callback upon completion.
void set_url(const std::string &host, const std::string &path, const std::string &query="")
Sets the WebSocket server URL with optional query parameters.
std::shared_ptr< IWebSocketClient > m_client
Pointer to the WebSocket client instance.
bool connect_and_wait()
Connects to the WebSocket server, blocking until the connection completes.
virtual ~WebSocketClient()
Destructor resets the WebSocket client instance.
std::future< bool > set_config(std::unique_ptr< WebSocketConfig > config)
Asynchronously sets the WebSocket configuration.
void connect(std::function< void(bool)> callback)
Connects to the WebSocket server and executes a callback upon completion.
void set_proxy(const std::string &ip, int port, const std::string &username, const std::string &password, ProxyType type=ProxyType::PROXY_HTTP)
Sets the proxy server address with authentication.
WebSocketClient()
Default constructor initializes the WebSocketClient.
void set_request_timeout(long request_timeout)
Sets the timeout for WebSocket requests.
std::future< bool > connect()
Asynchronously connects to the WebSocket server.
bool send_message(const std::string &message, long rate_limit_id=0, std::function< void(const std::error_code &)> callback=nullptr)
Sends a message through the WebSocket.
std::future< bool > disconnect()
Asynchronously disconnects from the WebSocket server.
Headers get_headers() const
Retrieves the headers associated with the WebSocket connection.
Configuration parameters for establishing and managing WebSocket connections.
static WebSocketManager & get_instance()
Get the singleton instance of WebSocketManager.
std::shared_ptr< IWebSocketClient > create_client()
Creates and returns a new WebSocket client instance based on the platform defined by compilation flag...
void notify()
Notifies the worker to begin processing requests or tasks.
static NetworkWorker & get_instance()
Get the singleton instance of NetworkWorker.
void add_task(std::function< void()> task)
Adds a task to the queue and notifies the worker thread.
void start(const bool use_async)
Starts the worker thread for asynchronous task processing.
#define KURLYK_AUTO_INIT_USE_ASYNC
Determines whether the NetworkWorker runs in a background thread during automatic initialization.
Definition kurlyk.hpp:20
Primary namespace for the Kurlyk library, encompassing initialization, request management,...
ProxyType
Enumeration of supported proxy types compatible with libcurl.
Definition enums.hpp:12
@ PROXY_HTTP
HTTP proxy.
Definition enums.hpp:13
utils::CaseInsensitiveMultimap Headers
Alias for HTTP headers, providing a case-insensitive unordered multimap.
utils::CaseInsensitiveMultimap QueryParams
Alias for query parameters in HTTP requests, stored case-insensitively.