简单的udp客户端提升

simple udp client boost

我正在尝试编写一个简单的客户端来向服务器发布 UDP 消息。我的缓冲区没有作为 udp 发送。当我尝试将消息发送到 netcat 时,它没有出现。

#include <iostream>
#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/thread.hpp>

int main(int argc, char *argv[])
{
boost::asio::io_service io_service;
boost::asio::ip::udp::endpoint endpoint_(boost::asio::ip::address::from_string("0.0.0.0"), 2399);
boost::asio::ip::udp::socket socket(io_service, endpoint_);
boost::asio::socket_base::broadcast option(true);
socket.set_option(option);
char*  data = "hello";
socket.send_to(boost::asio::buffer(data, strlen(data)), endpoint_);
getchar();
return 0;
}

将套接字绑定到端点是服务器功能。如果已经在该端口上侦听某些内容,您可能会收到 "Bind error/Address already in use" 错误,您可能会注意到这一点。

改为使用socket.open:

Live On Coliru

#include <iostream>
#include <boost/asio.hpp>

int main()
{
    using namespace boost::asio;
    using ip::udp;
    io_service io_service;

    udp::socket socket(io_service);
    socket.open(udp::v4());
    socket.set_option(socket_base::broadcast(true));

    const char* data = "hello";
    udp::endpoint endpoint_(ip::address::from_string("0.0.0.0"), 2399);
    socket.send_to(boost::asio::buffer(data, strlen(data)), endpoint_);
}