This commit is contained in:
azw 2023-05-06 11:17:29 +00:00
parent f2a0062ee7
commit f48b48638e
2 changed files with 26 additions and 20 deletions

View File

@ -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<std::mutex>();
}
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<std::mutex> 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

View File

@ -30,22 +30,21 @@ namespace a8
private:
void HandleConnect(const asio::error_code& err, const tcp::endpoint& endpoint);
void DoRead();
private:
std::shared_ptr<asio::ip::tcp::resolver> resolver_;
std::shared_ptr<asio::ip::tcp::socket> socket_;
volatile bool actived_ = false;
volatile bool connected_ = false;
std::mutex* send_buffer_mutex_ = nullptr;
std::shared_ptr<std::mutex> 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<char, 1024 * 64> buffer_;
void SetActive(bool active);
void ActiveStart();
void ActiveStop();
void NotifySendCond();
};
}