#include "dl_net.h" #include 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; ClientImp() : _socket{ _ioContext } {} }; // tcp一个连接 class ServerConnect { public: ServerConnect(asio::io_context& context) : _socket{ context } { _buf.resize(DEFAULT_BUFFER_SIZE); _read_head(); } void Start() {} asio::ip::tcp::socket _socket; MsgHead _head; Buffer _buf; private: void _read_head() { // 读头 asio::async_read(_socket, asio::buffer(&_head, sizeof(MsgHead)), [&](asio::error_code ec, size_t size) { if (size == 0) { _read_head(); return; } if (_head._magic != NETWORK_MESSAGE_TAG) { log_warn("不合法的包:{}", _head._magic); return; } log_msg("包大小:{}", _head._size); _read_tail(_head._size); }); } void _read_tail(uint32_t size) { _buf.resize(size); asio::async_read(_socket, asio::buffer(_buf.data(), size), [&](asio::error_code ec, size_t s) { assert(s == size); log_msg("{}", to_string(_buf)); _read_head(); }); } }; // tcp服务器 class ServerImp { public: asio::io_context _ioContext; asio::ip::tcp::acceptor _acceptor; std::list _allConnect; ServerImp() : _acceptor{ _ioContext , asio::ip::tcp::endpoint{asio::ip::tcp::v4(), 7000} } { } ~ServerImp() { _ioContext.stop(); for (auto& iter : _allConnect) { delete iter; } } bool _accept() { try { // 创建一个待连接 ServerConnect* sc = new ServerConnect(_ioContext); _allConnect.push_back(sc); // 异步accept _acceptor.async_accept(sc->_socket, std::bind(&ServerImp::_accept_handler, this, sc, 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) { sc->Start(); } _accept(); } }; // 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() { _ioContext.stop(); } 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_err("{}", e.what()); } return false; } void _read_handler(std::error_code ec, size_t length) { /*机翻:如果数据报或消息大于指定的缓冲区,则缓冲区将填充数据报的第一部分,并且 recv 会生成错误 WSAEMSGSIZE。 对于不可靠的协议(例如 UDP),多余的数据会丢失; 对于可靠协议,数据由服务提供商保留,直到通过调用具有足够大缓冲区的 RECV 成功读取数据。*/ UdpMessage msg; msg._buf = _buf; 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 Network::GetIpAddressLocal(bool ipv4 /*= true*/) { std::vector 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 = resolver.resolve(query); asio::ip::tcp::resolver::iterator end; for (; endpoint_iterator != end; ++endpoint_iterator) { asio::ip::basic_endpoint 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() { try { asio::ip::tcp::resolver r{ _imp->_ioContext }; asio::ip::tcp::resolver::query q{ "127.0.0.1", "7000" }; asio::ip::tcp::resolver::results_type vec_ed = r.resolve(q); connect(_imp->_socket, vec_ed); _t = g_thread->Create(); _t->Start(_thread_run, this); return true; } catch (std::exception& e) { log_err("{}", dl::CodeCvt::Utf8ToMultiByte(e.what())); } return false; } void Client::Send(BufferView buf) { _bufList.Add(CreateBuffer(buf)); } Client::Client() : _t{ nullptr }, _bEnd{ false } { _imp = new ClientImp; } Client::~Client() { _bEnd = true; delete _imp; delete _t; } void Client::_thread_run(void* p) { // 子线程 Client* c = (Client*)p; while (!c->_bEnd) { Buffer* buf = c->_bufList.Beg(); if(!buf) continue; // std::error_code ec; MsgHead head; head._magic = NETWORK_MESSAGE_TAG; head._size = (uint32_t)buf->size(); head._check = 0; head._compress = 0; asio::write(c->_imp->_socket, asio::buffer(&head, sizeof(MsgHead))); size_t size = asio::write(c->_imp->_socket, asio::buffer(*buf)); assert(size == buf->size()); c->_bufList.End(); } } //--------------------------------------Tcp Server bool Server::Accept() { try { _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); } Server::Server() : _t{ nullptr } { _imp = new ServerImp; } Server::~Server() { delete _imp; delete _t; } 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 = c->_bufListSend.Beg(); if(!buf) 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("ClientUdp Send >> [{}:{}]:\n{}", c->_imp->_endpoint.address().to_string(), c->_imp->_endpoint.port(), to_string_auto(*buf)); #endif c->_bufListSend.End(); } } 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("ClientUdp Recv << [{}:{}]:\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); } ServerUdp::ServerUdp() { _imp = new ServerUdpImp(this); } ServerUdp::~ServerUdp() { delete _imp; delete _t; } void ServerUdp::_thread_run(void* p) { //-----------------------子线程---------------------------- ServerUdp* s = (ServerUdp*)p; s->_imp->_ioContext.run(); } }