From 0b907a864891cac59de925693e9a666e8a9869e1 Mon Sep 17 00:00:00 2001 From: xia-chu <771730766@qq.com> Date: Wed, 1 Nov 2023 17:20:59 +0800 Subject: [PATCH] =?UTF-8?q?=E7=A1=AE=E4=BF=9DUdpServer=E5=88=9B=E5=BB=BA?= =?UTF-8?q?=E8=B5=84=E6=BA=90=E5=B0=B1=E7=BB=AA=E5=90=8E=E5=86=8D=E5=BC=80?= =?UTF-8?q?=E5=A7=8B=E7=BD=91=E7=BB=9C=E4=BA=8B=E4=BB=B6=E7=9B=91=E5=90=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Network/UdpServer.cpp | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/src/Network/UdpServer.cpp b/src/Network/UdpServer.cpp index 50ca26de1..2a027d1e4 100644 --- a/src/Network/UdpServer.cpp +++ b/src/Network/UdpServer.cpp @@ -74,11 +74,6 @@ void UdpServer::start_l(uint16_t port, const std::string &host) { //主server才创建session map,其他cloned server共享之 _session_mutex = std::make_shared(); _session_map = std::make_shared >(); - if (!_socket->bindUdpSock(port, host.c_str())) { - // udp 绑定端口失败, 可能是由于端口占用或权限问题 - std::string err = (StrPrinter << "Bind udp socket on " << host << " " << port << " failed: " << get_uv_errmsg(true)); - throw std::runtime_error(err); - } // 新建一个定时器定时管理这些 udp 会话,这些对象只由主server做超时管理,cloned server不管理 std::weak_ptr weak_self = std::static_pointer_cast(shared_from_this()); @@ -105,6 +100,21 @@ void UdpServer::start_l(uint16_t port, const std::string &host) { } }); + if (!_socket->bindUdpSock(port, host.c_str())) { + // udp 绑定端口失败, 可能是由于端口占用或权限问题 + std::string err = (StrPrinter << "Bind udp socket on " << host << " " << port << " failed: " << get_uv_errmsg(true)); + throw std::runtime_error(err); + } + + for (auto &pr: _cloned_server) { + // 启动子Server +#if 0 + pr.second->_socket->cloneSocket(*_socket); +#else + // 实验发现cloneSocket方式虽然可以节省fd资源,但是在某些系统上线程漂移问题更严重 + pr.second->_socket->bindUdpSock(_socket->get_local_port(), _socket->get_local_ip()); +#endif + } InfoL << "UDP server bind to [" << host << "]: " << port; } @@ -125,13 +135,6 @@ void UdpServer::cloneFrom(const UdpServer &that) { _session_map = that._session_map; // clone properties this->mINI::operator=(that); - // clone udp socket -#if 0 - _socket->cloneSocket(*(that._socket)); -#else - // 实验发现cloneSocket方式虽然可以节省fd资源,但是在某些系统上线程漂移问题更严重 - _socket->bindUdpSock(that._socket->get_local_port(), that._socket->get_local_ip()); -#endif } void UdpServer::onRead(const Buffer::Ptr &buf, sockaddr *addr, int addr_len) {