udp 广播客户端类12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273class UdpClientTest{public: UdpClientTest(boost::asio::io_context& io) : io_context_(io) , socket_(io_context_) { } bool IsInit() { return m_init; } bool Init(unsigned short port ) { if (m_init) return false; try { socket_.open(boost::asio::ip::udp::v4()); socket_.bind(boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), port)); boost::asio::ip::udp::endpoint remote_endpoint; m_init = true; } catch (std::exception& e) { m_init = false; LOG_ERROR("errmsg=%s",e.what()); } return m_init; } int RecvFrom(char* buff, int size, boost::asio::ip::udp::endpoint& remote_endpoint) { //boost::asio::ip::udp::endpoint remote_endpoint; size_t len = -1; try { boost::system::error_code ignored_error; len = socket_.receive_from(boost::asio::buffer(buff, size), remote_endpoint); } catch (std::exception& e) { LOG_ERROR("errmsg=%s",e.what()); len = -1; } return len; } int RecvFrom(char *buff, int size, std::string &address, unsigned short &port) { int len = -1; boost::asio::ip::udp::endpoint remote_endpoint; len = RecvFrom(buff, size, remote_endpoint); if (len > 0) { address = remote_endpoint.address().to_string(); port = remote_endpoint.port(); } return len; }private: bool m_init{ false }; boost::asio::io_context& io_context_; boost::asio::ip::udp::socket socket_;}; 使用1234567891011121314151617UdpClientTest m_udpClient(m_ioContext); //LOG_TRACE("%s", "udp init with 27777!"); if (!m_udpClient.IsInit() && !m_udpClient.Init(27777)) { //LOG_ERROR("%s","udp init error!"); break; } char buff[1024]; unsigned short remotePort; std::string remote; int len = m_udpClient.RecvFrom(buff, 1024, remote, remotePort); if (len < 0 || len >= 1024) { //LOG_ERROR("udp recv server info error, length too long. length=%d", len); break; }