Files
dl_old/dl/io/dl_net.cpp
T
2026-03-15 13:51:27 +08:00

949 lines
18 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include "dl_net.h"
#include <asio.hpp>
#include "system/dl_time.h"
namespace dl
{
Network* g_net;
constexpr size_t DEFAULT_BUFFER_SIZE = 1024;
//------------------------------------Declare--------------------------------
// tcp客户端
class ClientImp
{
public:
asio::io_context _ioContext;
asio::ip::tcp::socket _socket;
std::string _remoteIp;
uint16_t _remotePort;
ClientImp() :
_socket{ _ioContext }
{}
void _handle_error(asio::error_code ec)
{
std::string str = fmt::format("连接中断->[{}:{}]:", _remoteIp, _remotePort);
if (ec == asio::error::eof)
{
str += "正常断开";
log_info0(str);
}
else if (ec == asio::error::connection_reset)
{
str += "连接被重置";
log_warn0(str);
}
else if (ec != asio::error::operation_aborted)
{
str += dl::to_string(ec);
log_err0(str);
}
}
};
// tcp一个连接
class ServerConnect
{
public:
ServerConnect(ServerImp* parent, asio::io_context& context) :
_parent{ parent },
_socket{ context },
_bDelete{ false },
_eventCount{ 0 }
{
_buf.resize(DEFAULT_BUFFER_SIZE);
}
void Start()
{
//_socketId = _socket.native_handle();
try
{
_remoteIp = _socket.remote_endpoint().address().to_string();
_remotePort = _socket.remote_endpoint().port();
}
catch (...)
{
log_info("创建连接失败!");
return;
}
log_info("创建连接->[{}:{}]", _remoteIp, _remotePort);
_read_head();
_write_head();
}
void Send(uint32_t msg_id, BufferView buf);
ServerImp* _parent;
asio::ip::tcp::socket _socket;
std::string _remoteIp;
uint16_t _remotePort;
MsgHead _head;
Buffer _buf;
TcpMessageList _msgListSend;
TcpMessage _msgSend;
bool _bDelete; // 删除标记(设置后等待事件全部完成)
unsigned _eventCount; // 事件计数器(删除标记,且计数为0,则可以删除自己)
~ServerConnect();
private:
void _read_head();
void _read_tail(uint32_t size);
void _write_head();
void _write_tail(uint32_t size);
};
// tcp服务器
class ServerImp
{
public:
asio::io_context _ioContext;
asio::ip::tcp::acceptor _acceptor;
std::unordered_map<int, ServerConnect*> _allConnect;
// 待处理数据(按顺序)
std::list<TcpMessageServer> _allMsg;
// 待处理数据(按用户)TODO
std::unordered_map<int, TcpMessage> _allMsgUser;
std::mutex _mutexMsg;
ServerConnect* _scFree; // 空闲连接
Server::CbDisconnect _cbDisconnect;
ServerImp() :
_acceptor{ _ioContext }
{
}
~ServerImp()
{
delete _scFree;
for (auto& iter : _allConnect)
{
delete iter.second;
}
}
bool _accept()
{
try
{
// 创建一个待连接
_scFree = new ServerConnect(this, _ioContext);
// 异步accept
_acceptor.async_accept(_scFree->_socket,
std::bind(&ServerImp::_accept_handler, this, _scFree, std::placeholders::_1));
return true;
}
catch (std::exception& e)
{
log_err("{}", e.what());
}
return false;
}
void _accept_handler(ServerConnect* sc, std::error_code ec)
{
if (ec)
{
_handle_error(sc, ec);
delete sc;
}
else
{
// todo id复用问题
int socket_id = (int)sc->_socket.native_handle();
assert(_allConnect.find(socket_id) == _allConnect.end());
_allConnect[socket_id] = sc;
sc->Start();
}
_accept();
}
void _handle_error(ServerConnect* sc, std::error_code ec)
{
std::string str = fmt::format("连接中断->[{}:{}]:", sc->_remoteIp, sc->_remotePort);
if (ec == asio::error::eof)
{
str += "正常断开";
log_info0(str);
}
else if (ec == asio::error::connection_reset)
{
str += "连接被重置";
log_warn0(str);
}
else if (ec != asio::error::operation_aborted)
{
str += dl::to_string(ec);
log_err0(str);
}
}
void _remove_connect(ServerConnect* sc)
{
log_info("移除连接->[{}:{}]", sc->_remoteIp, sc->_remotePort);
sc->_bDelete = true;
int socket_id = (int)sc->_socket.native_handle();
_allConnect.erase(socket_id);
if (_cbDisconnect)
_cbDisconnect(socket_id);
try
{
sc->_socket.shutdown(asio::socket_base::shutdown_both);
sc->_socket.close();
}
catch (...)
{
}
}
};
// udp客户端
class ClientUdpImp
{
public:
asio::io_context _ioContext;
asio::ip::udp::endpoint _endpoint;
asio::ip::udp::socket _socket;
ClientUdpImp() :
_socket{ _ioContext }
{}
void _init(const asio::ip::address& addr, asio::ip::port_type port, bool broadcast)
{
_endpoint = asio::ip::udp::endpoint{ addr, port };
_socket.open(_endpoint.protocol());
if (broadcast)
_socket.set_option(asio::socket_base::broadcast(true));
}
};
// udp服务器
class ServerUdpImp
{
public:
ServerUdp* _parent;
asio::io_context _ioContext;
asio::ip::udp::socket _socket;
asio::ip::udp::endpoint _endpoint; // 目标,接收到后被填充
Buffer _buf;
ServerUdpImp(ServerUdp* parent) :
_parent{ parent },
_socket{ _ioContext }
{
_buf.resize(DEFAULT_BUFFER_SIZE);
}
~ServerUdpImp()
{
}
void _init(const asio::ip::address& addr, asio::ip::port_type port)
{
asio::ip::udp::endpoint listen_endpoint{ addr, port };
_socket.open(listen_endpoint.protocol());
_socket.set_option(asio::ip::udp::socket::reuse_address(true));
_socket.bind(listen_endpoint);
// 广播不需要加入多播组
// Join the multicast group.
/*socket_.set_option(
asio::ip::multicast::join_group(multicast_address));*/
}
bool _read()
{
try
{
// 异步 read
_socket.async_receive_from(asio::buffer(_buf), _endpoint,
std::bind(&ServerUdpImp::_read_handler, this, std::placeholders::_1, std::placeholders::_2));
return true;
}
catch (std::exception& e)
{
log_err0(e);
}
return false;
}
void _read_handler(std::error_code ec, size_t length)
{
/*机翻:如果数据报或消息大于指定的缓冲区,则缓冲区将填充数据报的第一部分,并且 recv 会生成错误 WSAEMSGSIZE。
对于不可靠的协议(例如 UDP),多余的数据会丢失;
对于可靠协议,数据由服务提供商保留,直到通过调用具有足够大缓冲区的 RECV 成功读取数据。*/
UdpMessage msg;
msg._buf = { _buf.begin(), _buf.begin() + length };
msg._ip = _endpoint.address().to_string();
msg._port = _endpoint.port();
_parent->_listMsg.Add(msg);
#ifdef DL_NETWORK_DEBUG_INFO
log_msg("ServerUDP Recv << [{}:{}]:\n{}", _endpoint.address().to_string(), _endpoint.port(),
to_string_auto(CreateBufferView(_buf, length)));
#endif
_read();
}
};
//---------------------------------------Implement--------------------------------------
std::string Network::GetHostName()
{
return asio::ip::host_name();
}
std::vector<std::string> Network::GetIpAddressLocal(bool ipv4 /*= true*/)
{
std::vector<std::string> ret;
asio::io_service io_service;
asio::ip::tcp::resolver resolver(io_service);
asio::ip::tcp::resolver::query query(asio::ip::host_name(), "");
asio::ip::tcp::resolver::iterator endpoint_iterator;
try
{
// 无网卡时,异常
endpoint_iterator = resolver.resolve(query);
}
catch (...)
{
return {};
}
asio::ip::tcp::resolver::iterator end;
for (; endpoint_iterator != end; ++endpoint_iterator)
{
asio::ip::basic_endpoint<asio::ip::tcp> ep = endpoint_iterator->endpoint();
if (!ep.address().is_loopback()
&& ep.address().is_v4() == ipv4)
{
ret.push_back(ep.address().to_string());
}
}
return ret;
}
//--------------------------------------Tcp Client
bool Client::Connent(std::string_view ip, uint16_t port)
{
try
{
asio::ip::tcp::resolver r{ _imp->_ioContext };
asio::ip::tcp::resolver::query q{ ip.data(), std::to_string(port) };
asio::ip::tcp::resolver::results_type vec_ed =
r.resolve(q);
asio::connect(_imp->_socket, vec_ed);
_tSend = g_thread->Create();
_tSend->Start(_thread_send, this);
_tRecv = g_thread->Create();
_tRecv->Start(_thread_recv, this);
_imp->_remoteIp = _imp->_socket.remote_endpoint().address().to_string();
_imp->_remotePort = _imp->_socket.remote_endpoint().port();
return true;
}
catch (std::exception& e)
{
log_warn("连接失败->[{}:{}] {}", ip, port, dl::to_string(e));
}
return false;
}
void Client::Send(uint32_t msg_id, BufferView buf)
{
TcpMessage msg;
msg._head._id = msg_id;
msg._buf = CreateBuffer(buf);
_bufListSend.Add(msg);
}
std::string Client::GetRemoteAddressString()
{
return fmt::format("{}:{}", _imp->_remoteIp, _imp->_remotePort);
}
Client::Client() :
_tSend{ nullptr },
_tRecv{ nullptr },
_bEnd{ false }
{
_imp = new ClientImp;
}
Client::~Client()
{
_bEnd = true;
if (_tRecv)
{
// 关闭发送(发送FIN包)
{
asio::error_code ec;
_imp->_socket.shutdown(asio::socket_base::shutdown_send, ec);
if (ec)
log_err0(ec);
// 等待发送线程结束
while (!_tSend->IsFinish())
{
g_time->Sleep();
}
}
// 关闭接收
{
// 等待接收线程结束(服务器返回eof)
while (!_tRecv->IsFinish())
{
g_time->Sleep();
}
}
{
asio::error_code ec;
_imp->_socket.close(ec);
if (ec)
log_err0(ec);
}
}
delete _imp;
delete _tSend;
delete _tRecv;
}
void Client::_thread_send(void* p)
{
// 子线程
Client* c = (Client*)p;
while (!c->_bEnd)
{
TcpMessage msg;
if (!c->_bufListSend.PopFront(msg))
{
g_time->Sleep();
continue;
}
//
std::error_code ec;
size_t size;
msg._head._size = (uint32_t)msg._buf.size();
msg._head._check = 0;
msg._head._compress = 0;
msg._head._magic = NETWORK_MESSAGE_TAG;
try
{
asio::write(c->_imp->_socket, asio::buffer(&msg._head, sizeof(MsgHead)));
size = asio::write(c->_imp->_socket, asio::buffer(msg._buf));
}
catch (std::system_error& e)
{
c->_imp->_handle_error(e.code());
return;
}
assert(size == msg._buf.size());
if (NETWORK_LOG_LOW)
{
log_msg(
"上行->[{}:{}]:\n"
"消息id:{}\n"
"数据大小:{}\n"
"{}",
c->_imp->_remoteIp,
c->_imp->_remotePort,
msg._head._id, msg._head._size,
to_string_auto(msg._buf));
}
}
}
void Client::_thread_recv(void* p)
{
// 子线程
Client* c = (Client*)p;
while (!c->_bEnd)
{
std::error_code ec;
TcpMessage msg;
size_t size = 0;
try
{
c->_imp->_socket.read_some(asio::buffer(&msg._head, sizeof(MsgHead)));
//
msg._buf.resize(msg._head._size);
size = c->_imp->_socket.read_some(asio::buffer(msg._buf));
}
catch (std::system_error& e)
{
c->_imp->_handle_error(e.code());
return;
}
assert(size == msg._buf.size());
if (NETWORK_LOG_LOW)
{
log_msg("下行<-[{}:{}]:\n"
"消息id:{}\n"
"数据大小:{}\n"
"{}",
c->_imp->_remoteIp,
c->_imp->_remotePort,
msg._head._id,
msg._head._size,
to_string_auto(msg._buf));
}
c->_bufListRecv.Add(msg);
}
}
//--------------------------------------Tcp Server
bool Server::Accept(uint16_t port)
{
try
{
_imp->_acceptor = asio::ip::tcp::acceptor{ _imp->_ioContext,
asio::ip::tcp::endpoint{asio::ip::tcp::v4(), port} };
_imp->_accept();
return true;
}
catch (std::exception& e)
{
log_err("{}", e.what());
}
return false;
}
void Server::Run()
{
_t = g_thread->Create();
_t->Start(_thread_run, this);
}
void Server::SetCbDisconnect(CbDisconnect func)
{
_imp->_cbDisconnect = func;
}
void Server::_send_imp(int sokect_id, uint32_t msg_id, BufferView buf)
{
auto iter = _imp->_allConnect.find(sokect_id);
if (iter == _imp->_allConnect.end())
{
log_warn("目标无效->[sosket:{}]", sokect_id);
return;
}
ServerConnect* sc = iter->second;
sc->Send(msg_id, buf);
}
std::string Server::GetIp()
{
return _imp->_acceptor.local_endpoint().address().to_string();
}
uint16_t Server::GetPort()
{
return _imp->_acceptor.local_endpoint().port();
}
TcpMessageServer* Server::_get_pop_msg()
{
std::lock_guard guard{ _imp->_mutexMsg };
if (_imp->_allMsg.empty())
return nullptr;
_msgTemp = _imp->_allMsg.front();
_imp->_allMsg.pop_front();
return &_msgTemp;
}
std::string Server::GetRemoteAddressString(int socket_id)
{
auto iter = _imp->_allConnect.find(socket_id);
if (iter == _imp->_allConnect.end())
{
log_warn("目标无效->[sosket:{}]", socket_id);
return {};
}
ServerConnect* sc = iter->second;
return fmt::format("{}:{}", sc->_remoteIp, sc->_remotePort);
}
Server::Server() :
_t{ nullptr }
{
_imp = new ServerImp;
}
Server::~Server()
{
_imp->_ioContext.stop();
// 先删除线程,等待执行完后,再删自己
delete _t;
delete _imp;
}
void Server::_thread_run(void* p)
{
// 子线程
Server* s = (Server*)p;
s->_imp->_ioContext.run();
}
//--------------------------------------Udp Client
//bool ClientUdp::Connent()
//{
// _imp->_endpoint( { asio::ip::make_address(ip), port };
// _imp->
//
// _t = g_thread->Create();
// _t->Start(_thread_run, this);
//
// return true;
//}
ClientUdp::ClientUdp() :
_bEnd{ false },
_tSend{ nullptr },
_tRecv{ nullptr }
{
_imp = new ClientUdpImp();
}
ClientUdp::~ClientUdp()
{
_bEnd = true;
delete _imp;
delete _tSend;
delete _tRecv;
}
void ClientUdp::SetAddress(std::string_view ip, uint16_t port, bool broadcast /*= false*/)
{
_imp->_init(asio::ip::make_address(ip), port, broadcast);
}
void ClientUdp::Send(BufferView buf)
{
if (!_tSend)
{
_tSend = g_thread->Create();
_tSend->Start(_thread_send, this);
_tRecv = g_thread->Create();
_tRecv->Start(_thread_recv, this);
}
_bufListSend.Add(CreateBuffer(buf));
}
void ClientUdp::_thread_send(void* p)
{
// 子线程
ClientUdp* c = (ClientUdp*)p;
while (!c->_bEnd)
{
Buffer buf;
if (!c->_bufListSend.PopFront(buf))
{
g_time->Sleep();
continue;
}
//
std::error_code ec;
size_t size;
try
{
size = c->_imp->_socket.send_to(asio::buffer(buf), c->_imp->_endpoint);
}
catch (std::system_error& e)
{
log_err0(e);
}
assert(size == buf.size());
#ifdef DL_NETWORK_DEBUG_INFO
log_msg("上行->[{}:{}]:\n{}",
c->_imp->_endpoint.address().to_string(), c->_imp->_endpoint.port(),
to_string_auto(buf));
#endif
}
}
void ClientUdp::_thread_recv(void* p)
{
// 子线程
ClientUdp* c = (ClientUdp*)p;
while (!c->_bEnd)
{
std::error_code ec;
Buffer buf;
size_t size;
try
{
size = c->_imp->_socket.receive_from(asio::buffer(buf), c->_imp->_endpoint);
}
catch (std::system_error& e)
{
if(e.code().value() == 10004)
break;
log_err0(e);
}
assert(size == buf.size());
#ifdef DL_NETWORK_DEBUG_INFO
log_msg("下行<-[{}:{}]:\n{}",
c->_imp->_endpoint.address().to_string(), c->_imp->_endpoint.port(),
to_string_auto(buf));
#endif
c->_bufListRecv.Add(buf);
}
}
//--------------------------------------Udp Server
void ServerUdp::Start(std::string_view ip, uint16_t port)
{
_imp->_init(asio::ip::make_address(ip), port);
_imp->_read();
_t = g_thread->Create();
_t->Start(_thread_run, this);
}
std::string ServerUdp::GetIp()
{
return _imp->_socket.local_endpoint().address().to_string();
}
uint16_t ServerUdp::GetPort()
{
return _imp->_socket.local_endpoint().port();
}
ServerUdp::ServerUdp()
{
_imp = new ServerUdpImp(this);
}
ServerUdp::~ServerUdp()
{
_imp->_ioContext.stop();
// 先删除线程,等待执行完后,再删自己
delete _t;
delete _imp;
}
void ServerUdp::_thread_run(void* p)
{
//-----------------------子线程----------------------------
ServerUdp* s = (ServerUdp*)p;
s->_imp->_ioContext.run();
}
void ServerConnect::Send(uint32_t msg_id, BufferView buf)
{
TcpMessage msg;
msg._head._id = msg_id;
msg._head._size = (uint32_t)buf.size();
msg._head._check = 0;
msg._head._compress = 0;
msg._head._magic = NETWORK_MESSAGE_TAG;
msg._head._pad = 0;
msg._buf = CreateBuffer(buf);
_msgListSend.Add(msg);
}
ServerConnect::~ServerConnect()
{
}
//--------------------------------------后置实现
void ServerConnect::_read_head()
{
++_eventCount;
// 读头
asio::async_read(_socket, asio::buffer(&_head, sizeof(MsgHead)),
[&](asio::error_code ec, size_t size)
{
--_eventCount;
if (_bDelete)
{
if (_eventCount == 0)
delete this;
return;
}
if (ec)
{
_parent->_handle_error(this, ec);
_parent->_remove_connect(this);
return;
}
if (size == 0)
{
g_time->Sleep();
_read_head();
return;
}
if (_head._magic != NETWORK_MESSAGE_TAG)
{
log_warn("无效包<-[{}:{}]", _remoteIp, _remotePort);
return;
}
_read_tail(_head._size);
});
}
void ServerConnect::_read_tail(uint32_t size)
{
++_eventCount;
_buf.resize(size);
asio::async_read(_socket, asio::buffer(_buf.data(), size),
[&, size](asio::error_code ec, size_t s)
{
--_eventCount;
if (_bDelete)
{
if (_eventCount == 0)
delete this;
return;
}
if (ec)
{
_parent->_handle_error(this, ec);
_parent->_remove_connect(this);
return;
}
assert(s == size);
TcpMessageServer msg;
msg._socketId = (int)_socket.native_handle();
msg._head = _head;
msg._buf = _buf;
if (NETWORK_LOG_LOW)
{
log_msg(
"下行<-[{}:{}]:\n"
"消息id:{}\n"
"数据大小:{}\n"
"{}",
_remoteIp,
_remotePort,
msg._head._id, msg._head._size,
to_string_auto(msg._buf));
}
_parent->_mutexMsg.lock();
_parent->_allMsg.push_back(msg);
_parent->_mutexMsg.unlock();
_read_head();
});
}
void ServerConnect::_write_head()
{
++_eventCount;
bool send = false;
if (_msgListSend.PopFront(_msgSend))
send = true;
// 写头
asio::async_write(_socket, asio::buffer(&_msgSend._head, send ? sizeof(MsgHead) : 0),
[&](asio::error_code ec, size_t size)
{
--_eventCount;
if (_bDelete)
{
if (_eventCount == 0)
delete this;
return;
}
if (ec)
{
_parent->_handle_error(this, ec);
_parent->_remove_connect(this);
return;
}
if (size == 0)
{
g_time->Sleep();
_write_head();
return;
}
_write_tail(_msgSend._head._size);
});
}
void ServerConnect::_write_tail(uint32_t size)
{
++_eventCount;
asio::async_write(_socket, asio::buffer(_msgSend._buf.data(), size),
[&, size](asio::error_code ec, size_t s)
{
--_eventCount;
if (_bDelete)
{
if (_eventCount == 0)
delete this;
return;
}
if (ec)
{
_parent->_handle_error(this, ec);
_parent->_remove_connect(this);
return;
}
assert(s == size);
if (NETWORK_LOG_LOW)
{
log_msg(
"上行->[{}:{}]:\n"
"消息id:{}\n"
"数据大小:{}\n"
"{}",
_remoteIp,
_remotePort,
_msgSend._head._id, _msgSend._head._size,
to_string_auto(_msgSend._buf));
}
_write_head();
});
}
}