1
1
#include " Connection.hpp"
2
2
#include " Exceptions.hpp"
3
+ #include < iostream>
3
4
4
5
namespace xapi
5
6
{
@@ -25,7 +26,19 @@ Connection::Connection(Connection &&other) noexcept
25
26
26
27
Connection::~Connection ()
27
28
{
28
- cancelAsyncOperations ();
29
+ m_cancellationSignal.emit (boost::asio::cancellation_type::all);
30
+ if (m_websocket.is_open ())
31
+ {
32
+ try
33
+ {
34
+ // Attempt a graceful WebSocket closure
35
+ m_websocket.close (boost::beast::websocket::close_code::normal );
36
+ }
37
+ catch (const boost::system ::system_error &e)
38
+ {
39
+ std::cerr << " Fatal error: " << e.what () << std::endl;
40
+ }
41
+ }
29
42
}
30
43
31
44
boost::asio::awaitable<void > Connection::connect (const boost::url &url)
@@ -79,7 +92,7 @@ boost::asio::awaitable<void> Connection::establishSSLConnection(
79
92
80
93
boost::asio::awaitable<void > Connection::disconnect ()
81
94
{
82
- cancelAsyncOperations ( );
95
+ m_cancellationSignal. emit (boost::asio::cancellation_type::all );
83
96
try
84
97
{
85
98
co_await m_websocket.async_close (boost::beast::websocket::close_code::normal , boost::asio::use_awaitable);
@@ -148,15 +161,17 @@ boost::asio::awaitable<void> Connection::startKeepAlive(boost::asio::cancellatio
148
161
const auto executor = co_await boost::asio::this_coro::executor;
149
162
boost::asio::steady_timer pingTimer (executor);
150
163
const auto pingInterval = std::chrono::seconds (20 );
164
+ bool canceled = true ;
151
165
152
- cancellationSlot.assign ([&]([[maybe_unused]] boost::asio::cancellation_type type) {
166
+ cancellationSlot.assign ([&](boost::asio::cancellation_type type) {
153
167
if (type == boost::asio::cancellation_type::all)
154
168
{
169
+ canceled = true ;
155
170
pingTimer.cancel ();
156
171
}
157
172
});
158
173
159
- while (true )
174
+ while (!canceled )
160
175
{
161
176
try
162
177
{
@@ -179,14 +194,5 @@ boost::asio::awaitable<void> Connection::startKeepAlive(boost::asio::cancellatio
179
194
}
180
195
}
181
196
182
- void Connection::cancelAsyncOperations () noexcept
183
- {
184
- m_cancellationSignal.emit (boost::asio::cancellation_type::all);
185
- if (m_websocket.is_open ())
186
- {
187
- m_websocket.next_layer ().next_layer ().cancel ();
188
- }
189
- }
190
-
191
197
} // namespace internals
192
198
} // namespace xapi
0 commit comments