-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathwebsocket_handler.cpp
87 lines (70 loc) · 2.79 KB
/
websocket_handler.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include "websocket_handler.h"
#include <iostream> // For debugging (optional)
#include "latency_module.h" // Include the LatencyModule header
WebSocketHandler::WebSocketHandler(const std::string& host, const std::string& port, const std::string& endpoint )
: ctx_(ssl::context::tlsv12_client),
resolver_(ioc_),
websocket_(ioc_, ctx_),
host_(host),
endpoint_(endpoint) {
//trade_execution_(trade_execution) { // Initialize the TradeExecution reference
// Load the default SSL certificates
ctx_.set_default_verify_paths();
}
void WebSocketHandler::connect() {
try {
// Resolve the host and port
auto const results = resolver_.resolve(host_, "443");
// Connect to the server
asio::connect(websocket_.next_layer().next_layer(), results.begin(), results.end());
// Perform the SSL handshake
websocket_.next_layer().handshake(ssl::stream_base::client);
// Perform the WebSocket handshake
websocket_.handshake(host_, endpoint_);
std::cout << "WebSocket connected successfully!" << std::endl;
}
catch (const std::exception& e) {
std::cerr << "Error during WebSocket connection: " << e.what() << std::endl;
}
}
void WebSocketHandler::onMessage(const std::string& message) {
// Parse the incoming message into JSON
json data = json::parse(message);
}
void WebSocketHandler::sendMessage(const json& message) {
try {
// Serialize the JSON message and send it
std::string message_str = message.dump();
websocket_.write(asio::buffer(message_str));
std::cout << "Sent message: " << message_str << std::endl;
}
catch (const std::exception& e) {
std::cerr << "Error sending message: " << e.what() << std::endl;
}
}
json WebSocketHandler::readMessage() {
try {
auto read_start = LatencyModule::start(); // Start timer for WebSocket message read
beast::flat_buffer buffer;
websocket_.read(buffer);
// Parse the received message as JSON
std::string message_str = beast::buffers_to_string(buffer.data());
std::cout << "Received message: " << message_str << std::endl;
// End the timer and log the latency
LatencyModule::end(read_start, "WebSocket Read Latency");
return json::parse(message_str);
}
catch (const std::exception& e) {
std::cerr << "Error reading message: " << e.what() << std::endl;
return json(); // Return an empty JSON object in case of error
}
}
void WebSocketHandler::close() {
try {
websocket_.close(beast::websocket::close_code::normal);
std::cout << "WebSocket connection closed." << std::endl;
}
catch (const std::exception& e) {
std::cerr << "Error closing WebSocket: " << e.what() << std::endl;
}
}