transm/net/net_base.cpp

95 lines
2.5 KiB
C++
Raw Normal View History

2024-12-11 10:22:14 +08:00
#include "net_base.h"
CTcpClient::CTcpClient(asio::io_context& io_context) : io_context_(io_context), socket_(io_context_)
2024-12-11 10:22:14 +08:00
{
}
2025-02-06 09:37:24 +08:00
CTcpClient::~CTcpClient() = default;
2024-12-11 10:22:14 +08:00
2024-12-11 23:23:48 +08:00
bool CTcpClient::connect(const std::string& host, const std::string& port)
2024-12-11 10:22:14 +08:00
{
try {
asio::ip::tcp::resolver resolver(io_context_);
asio::ip::tcp::resolver::results_type endpoints = resolver.resolve(host, port);
asio::connect(socket_, endpoints);
TLOGI("Connected to {}:{}", host, port);
2024-12-19 15:54:42 +08:00
is_normal_ = true;
2024-12-11 10:22:14 +08:00
return true;
} catch (const std::exception& ex) {
TLOGE("Connection failed: {}", ex.what());
2024-12-11 10:22:14 +08:00
return false;
}
}
2024-12-11 23:23:48 +08:00
void CTcpClient::disconnect()
2024-12-11 10:22:14 +08:00
{
if (socket_.is_open()) {
try {
2024-12-19 15:54:42 +08:00
socket_.shutdown(asio::ip::tcp::socket::shutdown_both);
2024-12-11 10:22:14 +08:00
socket_.close();
TLOGI("Disconnected.");
2024-12-11 10:22:14 +08:00
} catch (const std::exception& ex) {
TLOGE("Error during disconnection: {}", ex.what());
2024-12-11 10:22:14 +08:00
}
}
}
2024-12-11 23:23:48 +08:00
bool CTcpClient::send(const char* data, int len)
2024-12-11 10:22:14 +08:00
{
2024-12-19 15:54:42 +08:00
if (!is_normal_) {
TLOGE("abnormal state, will not send.");
2024-12-19 15:54:42 +08:00
return false;
}
2024-12-11 10:22:14 +08:00
try {
auto send_size = asio::write(socket_, asio::buffer(data, len));
// TLOGI("Need Send len: {} Real Send len: {}", len, send_size);
2024-12-11 10:22:14 +08:00
return static_cast<int>(send_size) == len;
} catch (const std::exception& ex) {
TLOGE("Send failed: {}", ex.what());
2024-12-11 10:22:14 +08:00
return false;
}
}
void CTcpClient::register_func(ExFun_t&& f)
2024-12-11 10:22:14 +08:00
{
2024-12-11 22:51:43 +08:00
fun_ = f;
}
2024-12-11 23:23:48 +08:00
void CTcpClient::async_recv()
2024-12-11 22:51:43 +08:00
{
auto self(shared_from_this());
socket_.async_read_some(asio::buffer(tmp_buf_), [this, self](std::error_code ec, std::size_t length) {
if (ec) {
2024-12-19 15:54:42 +08:00
is_normal_ = false;
if (ec.value() == 995) {
// 正常中止退出
return;
}
if (ec.value() == 125) {
TLOGI("{} exit.", __FUNCTION__);
return;
}
TLOGE("{} {} error => {}", __FUNCTION__, ec.value(), ec.message());
} else {
2024-12-11 22:51:43 +08:00
buffer_.push(tmp_buf_.data(), length);
while (true) {
auto* frame = CTransProtocal::parse(buffer_);
if (frame) {
if (fun_) {
fun_(frame);
}
delete frame;
continue;
2024-12-11 22:51:43 +08:00
}
break;
2024-12-11 22:51:43 +08:00
}
2024-12-11 23:23:48 +08:00
async_recv();
2024-12-11 22:51:43 +08:00
}
});
2024-12-11 10:22:14 +08:00
}
2025-02-06 09:37:24 +08:00
bool CTcpClient::is_normal() const
{
return is_normal_;
}