From a019e3f0eb6f79320473b479f4158dd1aa74de7d Mon Sep 17 00:00:00 2001 From: azw Date: Sat, 6 May 2023 09:30:13 +0000 Subject: [PATCH] 1 --- a8/asiotcpclient.cc | 50 ++++++++++++++++++++++++++++++++++++++++----- a8/asiotcpclient.h | 8 +++++++- 2 files changed, 52 insertions(+), 6 deletions(-) diff --git a/a8/asiotcpclient.cc b/a8/asiotcpclient.cc index 9d7d8c7..bf1168f 100644 --- a/a8/asiotcpclient.cc +++ b/a8/asiotcpclient.cc @@ -11,6 +11,8 @@ #include #include +#include + #include #include @@ -20,6 +22,7 @@ const int MAX_RECV_BUFFERSIZE = 1024 * 64; namespace a8 { + AsioTcpClient::AsioTcpClient() { send_buffer_mutex_ = new std::mutex(); @@ -54,9 +57,7 @@ namespace a8 bool AsioTcpClient::IsActive() { - #if 0 - return socket_ != a8::INVALID_SOCKET; - #endif + return actived_; } bool AsioTcpClient::Connected() @@ -87,15 +88,37 @@ namespace a8 void AsioTcpClient::SetActive(bool active) { + if (active) { + if (!IsActive()) { + ActiveStart(); + } + } else { + if (IsActive()) { + ActiveStop(); + } + } } - bool AsioTcpClient::ActiveStart() + void AsioTcpClient::ActiveStart() { - return true; + actived_ = true; + connected_ = false; + tcp::resolver::results_type endpoints = resolver_->resolve + (tcp::v4(), + remote_address.c_str(), + a8::XValue(remote_port).GetString().c_str()); + + asio::async_connect(*socket_, endpoints, + [this] (const asio::error_code& ec, + const tcp::endpoint& endpoint) + { + HandleConnect(ec, endpoint); + }); } void AsioTcpClient::ActiveStop() { + actived_ = true; connected_ = false; } @@ -105,6 +128,23 @@ namespace a8 send_cond_->notify_all(); } + void AsioTcpClient::HandleConnect(const asio::error_code& err, const tcp::endpoint& endpoint) + { + if (err) { + actived_ = false; + connected_ = false; + if (on_error) { + on_error(this, err.value()); + } + return; + } else { + connected_ = true; + if (on_connect) { + on_connect(this); + } + } + } + } #endif diff --git a/a8/asiotcpclient.h b/a8/asiotcpclient.h index 3f03ac9..246bf5e 100644 --- a/a8/asiotcpclient.h +++ b/a8/asiotcpclient.h @@ -4,6 +4,8 @@ #include +using asio::ip::tcp; + namespace a8 { @@ -26,9 +28,13 @@ namespace a8 bool Connected(); void SendBuff(const char* buff, unsigned int bufflen); + private: + void HandleConnect(const asio::error_code& err, const tcp::endpoint& endpoint); + private: std::shared_ptr resolver_; std::shared_ptr socket_; + volatile bool actived_ = false; volatile bool connected_ = false; std::mutex* send_buffer_mutex_ = nullptr; SendQueueNode *top_node_ = nullptr; @@ -37,7 +43,7 @@ namespace a8 std::condition_variable *send_cond_ = nullptr; void SetActive(bool active); - bool ActiveStart(); + void ActiveStart(); void ActiveStop(); void NotifySendCond(); };