如果之前已经回答了这个问题我提前道歉,但是我已经搜索过,发现什么都没有帮助我。 我试图从服务器广播到一组客户端来监听任何消息。当客户端收到广播消息时,它会向服务器发送另一条消息。
.--------.
.--------.|
.--------. address: any address: any .--------.||
| | port: any / \ port: 8888 | |||
| server |-( ----------->| address: broadcast |----------> )-| client ||'
| | \ port: 8888 / | |'
| | | |
'--------'-( <----------- ( address: server ) <---------- )-'--------'
( port: 8888 ? )
Server.cpp
#include <iostream>
#include <boost/asio.hpp>
#include <boost/array.hpp>
int main()
{
namespace ip = boost::asio::ip;
boost::asio::io_service io_service;
// Server binds to any address and any port.
ip::udp::socket socket(io_service,
ip::udp::endpoint(ip::udp::v4(), 0));
socket.set_option(boost::asio::socket_base::broadcast(true));
// Broadcast will go to port 8888.
ip::udp::endpoint broadcast_endpoint(ip::address_v4::broadcast(), 8888);
// Broadcast data.
boost::array<char, 4> buffer;
socket.send_to(boost::asio::buffer(buffer), broadcast_endpoint);
ip::udp::endpoint sender_endpoint;
std::size_t bytes_transferred = socket.receive_from(boost::asio::buffer(buffer), sender_endpoint);
std::cout << "Server got " << bytes_transferred << " bytes." << std::endl;
}
Client.cpp
#include <iostream>
#include <boost/asio.hpp>
#include <boost/array.hpp>
int main()
{
namespace ip = boost::asio::ip;
boost::asio::io_service io_service;
// Client binds to any address on port 8888 (the same port on which
// broadcast data is sent from server).
ip::udp::socket socket(io_service,
ip::udp::endpoint(ip::udp::v4(), 8888 ));
ip::udp::endpoint sender_endpoint;
// Receive data.
boost::array<char, 4> buffer;
std::size_t bytes_transferred = socket.receive_from(boost::asio::buffer(buffer), sender_endpoint);
std::cout << "Client got " << bytes_transferred << " bytes." << std::endl;
boost::asio::ip::udp::resolver resolver(io_service);
boost::asio::ip::udp::resolver::query query(boost::asio::ip::udp::v4(), "localhost", "8888");
boost::asio::ip::udp::resolver::iterator iter = resolver.resolve(query);
boost::asio::ip::udp::endpoint remote_endpoint = *iter;
socket.send_to(boost::asio::buffer(buffer), remote_endpoint);
}
client
收到broadcat消息,但server
未收到client
发送的消息。
提前致谢。