70 lines
1.7 KiB
C++
70 lines
1.7 KiB
C++
#include "net_base.h"
|
|
|
|
CServer::CServer()
|
|
{
|
|
}
|
|
|
|
CServer::~CServer()
|
|
{
|
|
}
|
|
|
|
CClient::CClient(const std::shared_ptr<spdlog::logger>& logger) : logger_(logger), io_context_(), socket_(io_context_)
|
|
{
|
|
}
|
|
|
|
CClient::~CClient()
|
|
{
|
|
}
|
|
|
|
bool CClient::Connect(const std::string& host, const std::string& port)
|
|
{
|
|
try {
|
|
asio::ip::tcp::resolver resolver(io_context_);
|
|
asio::ip::tcp::resolver::results_type endpoints = resolver.resolve(host, port);
|
|
asio::connect(socket_, endpoints);
|
|
logger_->info("Connected to {}:{}", host, port);
|
|
return true;
|
|
} catch (const std::exception& ex) {
|
|
logger_->error("Connection failed: {}", ex.what());
|
|
return false;
|
|
}
|
|
}
|
|
|
|
void CClient::Disconnect()
|
|
{
|
|
if (socket_.is_open()) {
|
|
try {
|
|
socket_.close();
|
|
logger_->info("Disconnected.");
|
|
} catch (const std::exception& ex) {
|
|
logger_->error("Error during disconnection: {}", ex.what());
|
|
}
|
|
}
|
|
}
|
|
|
|
bool CClient::Send(const char* data, int len)
|
|
{
|
|
try {
|
|
auto send_size = asio::write(socket_, asio::buffer(data, len));
|
|
logger_->info("Need Send len: {} Real Send len: {}", len, send_size);
|
|
return static_cast<int>(send_size) == len;
|
|
} catch (const std::exception& ex) {
|
|
logger_->error("Send failed: {}", ex.what());
|
|
return false;
|
|
}
|
|
}
|
|
|
|
std::string CClient::Receive()
|
|
{
|
|
try {
|
|
std::vector<char> buffer(1024);
|
|
size_t length = socket_.read_some(asio::buffer(buffer));
|
|
std::string received_data(buffer.data(), length);
|
|
logger_->info("Received data len: {}", length);
|
|
return received_data;
|
|
} catch (const std::exception& ex) {
|
|
logger_->error("Receive failed: {}", ex.what());
|
|
return "";
|
|
}
|
|
}
|