This commit is contained in:
azw 2023-05-06 09:30:13 +00:00
parent f7125c874e
commit a019e3f0eb
2 changed files with 52 additions and 6 deletions

View File

@ -11,6 +11,8 @@
#include <sys/epoll.h>
#include <netinet/tcp.h>
#include <boost/bind.hpp>
#include <a8/a8.h>
#include <a8/asiotcpclient.h>
@ -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

View File

@ -4,6 +4,8 @@
#include <asio.hpp>
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<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;
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();
};