udp 广播客户端类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73

class 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_;
};

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
UdpClientTest 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;
}