添加连接管理的互斥锁,增强多线程环境下的连接安全性;更新TCPClient以支持断开回调

This commit is contained in:
Ayndpa
2025-11-18 19:20:36 +08:00
parent b308a644ff
commit 676d39d6a2
5 changed files with 44 additions and 13 deletions

View File

@@ -1,7 +1,7 @@
#include "tcp_client.h"
#include <iostream>
TCPClient::TCPClient(const std::string& host, int port) : host_(host), port_(port), connected_(false), socket_(std::make_shared<tcp::socket>(io_context_)), work_(boost::asio::make_work_guard(io_context_)), buffer_(1024) {}
TCPClient::TCPClient(const std::string& host, int port) : host_(host), port_(port), connected_(false), disconnected_(false), socket_(std::make_shared<tcp::socket>(io_context_)), work_(boost::asio::make_work_guard(io_context_)), buffer_(1024) {}
TCPClient::~TCPClient() { disconnect(); }
@@ -26,6 +26,11 @@ bool TCPClient::connect() {
}
void TCPClient::disconnect() {
if (disconnected_) return;
disconnected_ = true;
if (disconnectCallback_) {
disconnectCallback_();
}
connected_ = false;
io_context_.stop();
if (clientThread_.joinable()) {
@@ -59,6 +64,10 @@ void TCPClient::setReceiveCallback(std::function<void(const char*, size_t)> call
receiveCallbackBytes_ = callback;
}
void TCPClient::setDisconnectCallback(std::function<void()> callback) {
disconnectCallback_ = callback;
}
void TCPClient::start_read() {
socket_->async_read_some(boost::asio::buffer(buffer_), [this](const boost::system::error_code& error, std::size_t bytes_transferred) {
handle_read(error, bytes_transferred);