2012-02-16 41 views
12

Tôi muốn phát các tin nhắn UDP tới tất cả các máy tính trong mạng cục bộ bằng cách sử dụng boost::asio. Làm việc thông qua các ví dụ tôi đã đưa raboost :: asio UDP phát sóng

try { 
    socket.open(boost::asio::ip::udp::v4()); 
    boost::asio::socket_base::broadcast option(true); 
    socket.set_option(option); 
    endpoint = boost::asio::ip::udp::endpoint(
     boost::asio::ip::address::from_string("192.168.1.255"), 
     port); 
} 
catch(std::exception &e) { 
} 

và muốn quảng bá thông điệp từ hàng đợi của tôi với

while(!queue.empty()) { 
    std::string message = queue.front(); 
    boost::system::error_code ignored_error; 
    socket.send_to(
     boost::asio::buffer(message), 
     endpoint, 
     0, ignored_error); 
    queue.pop_front(); 
} 

nhưng mã của tôi ném một ngoại lệ invalid argument ngoại lệ trong khối mã đầu tiên. Nó hoạt động tốt cho 127.0.0.1 mặc dù. Tôi đang làm gì sai?

Trả lời

22

Hãy thử đoạn mã sau đây để gửi một phát sóng UDP, sử dụng ba::ip::address_v4::broadcast() gọi để có được một thiết bị đầu cuối:

bs::error_code error; 
    ba::ip::udp::socket socket(_impl->_ioService); 

    socket.open(ba::ip::udp::v4(), error); 
    if (!error) 
    { 
     socket.set_option(ba::ip::udp::socket::reuse_address(true)); 
     socket.set_option(ba::socket_base::broadcast(true)); 

     ba::ip::udp::endpoint senderEndpoint(ba::ip::address_v4::broadcast(), port);    

     socket.send_to(data, senderEndpoint); 
     socket.close(error); 
    } 
+1

trình hoàn hảo. Cảm ơn. – nijansen

+0

Làm cách nào để tránh gửi tin nhắn cho chính mình? – yonutix

+2

@yonutix Không, đó là mục đích phát sóng để gửi tin nhắn cho tất cả (và tự là có cho). – MicroCheapFx

Các vấn đề liên quan