From f48b48638eee635424e02c2d17d84264476d9c2a Mon Sep 17 00:00:00 2001 From: azw Date: Sat, 6 May 2023 11:17:29 +0000 Subject: [PATCH] 1 --- a8/asiotcpclient.cc | 39 +++++++++++++++++++++++---------------- a8/asiotcpclient.h | 7 +++---- 2 files changed, 26 insertions(+), 20 deletions(-) diff --git a/a8/asiotcpclient.cc b/a8/asiotcpclient.cc index bf1168f..31f7b43 100644 --- a/a8/asiotcpclient.cc +++ b/a8/asiotcpclient.cc @@ -25,20 +25,12 @@ namespace a8 AsioTcpClient::AsioTcpClient() { - send_buffer_mutex_ = new std::mutex(); - send_cond_mutex_ = new std::mutex(); - send_cond_ = new std::condition_variable(); + send_buffer_mutex_ = std::make_shared(); } AsioTcpClient::~AsioTcpClient() { Close(); - delete send_buffer_mutex_; - send_buffer_mutex_ = nullptr; - delete send_cond_mutex_; - send_cond_mutex_ = nullptr; - delete send_cond_; - send_cond_ = nullptr; } void AsioTcpClient::Open() @@ -82,7 +74,6 @@ namespace a8 bot_node_ = p; } send_buffer_mutex_->unlock(); - NotifySendCond(); } } @@ -122,12 +113,6 @@ namespace a8 connected_ = false; } - void AsioTcpClient::NotifySendCond() - { - std::unique_lock lk(*send_cond_mutex_); - send_cond_->notify_all(); - } - void AsioTcpClient::HandleConnect(const asio::error_code& err, const tcp::endpoint& endpoint) { if (err) { @@ -142,9 +127,31 @@ namespace a8 if (on_connect) { on_connect(this); } + DoRead(); } } + void AsioTcpClient::DoRead() + { + socket_->async_read_some + (asio::buffer(buffer_), + [this](std::error_code ec, std::size_t bytes_transferred) + { + if (!ec) { + if (on_socketread) { + on_socketread(this, buffer_.data(), bytes_transferred); + } + DoRead(); + } else { + actived_ = false; + connected_ = false; + if (on_disconnect) { + on_disconnect(this); + } + } + }); + } + } #endif diff --git a/a8/asiotcpclient.h b/a8/asiotcpclient.h index 246bf5e..121f066 100644 --- a/a8/asiotcpclient.h +++ b/a8/asiotcpclient.h @@ -30,22 +30,21 @@ namespace a8 private: void HandleConnect(const asio::error_code& err, const tcp::endpoint& endpoint); + void DoRead(); private: std::shared_ptr resolver_; std::shared_ptr socket_; volatile bool actived_ = false; volatile bool connected_ = false; - std::mutex* send_buffer_mutex_ = nullptr; + std::shared_ptr send_buffer_mutex_; SendQueueNode *top_node_ = nullptr; SendQueueNode *bot_node_ = nullptr; - std::mutex *send_cond_mutex_ = nullptr; - std::condition_variable *send_cond_ = nullptr; + std::array buffer_; void SetActive(bool active); void ActiveStart(); void ActiveStop(); - void NotifySendCond(); }; }