* @brief Closes the connection to server synchronously. * @note It's a synchronous method, it will not return until websocket thread exits. */
| 447 | * @note It's a synchronous method, it will not return until websocket thread exits. |
| 448 | */ |
| 449 | void WebSocket::close(uint16_t code, std::string_view reason) |
| 450 | { |
| 451 | if (_state < State::CLOSING) |
| 452 | { |
| 453 | _closeCode = code; |
| 454 | _closeReason = reason; |
| 455 | |
| 456 | if (_service->is_open(0)) |
| 457 | { |
| 458 | _state = State::CLOSING; |
| 459 | |
| 460 | yasio::obstream obs(sizeof(code, reason.size())); |
| 461 | obs.write(_closeCode); |
| 462 | obs.write_bytes(reason); |
| 463 | |
| 464 | WebSocketProtocol::sendFrame(*this, obs.data(), obs.length(), ws::detail::opcode::close); |
| 465 | |
| 466 | _service->close(0); |
| 467 | |
| 468 | if (_transport) |
| 469 | { |
| 470 | _syncCloseState = std::make_shared<std::promise<int>>(); |
| 471 | int status = _syncCloseState->get_future().get(); |
| 472 | _syncCloseState.reset(); |
| 473 | AXLOGD("WebSocket close with status: {}", status); |
| 474 | } |
| 475 | else |
| 476 | { |
| 477 | _service->stop(); // stop internal service for sync close |
| 478 | _state = State::CLOSED; |
| 479 | AXLOGW("WebSocket::close: connection not ready!"); |
| 480 | } |
| 481 | } |
| 482 | else |
| 483 | _state = State::CLOSED; |
| 484 | } |
| 485 | } |
| 486 | |
| 487 | /** |
| 488 | * @brief Closes the connection to server asynchronously. |
no test coverage detected