asio 广播代码示例
Posted itdef
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了asio 广播代码示例相关的知识,希望对你有一定的参考价值。
代码网络收集 修改了一个编译的小问题
客户端
// Client.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <boost/asio.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; char buf[500] = { 0 }; std::size_t bytes_transferred = socket.receive_from(boost::asio::buffer(buf), sender_endpoint); std::cout << "got " << bytes_transferred << " bytes." << buf <<std::endl; }
服务端
// Server.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <boost/asio.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; char* buf = "测试代码"; socket.send_to(boost::asio::buffer(buf,strlen(buf)+1), broadcast_endpoint); }
以上是关于asio 广播代码示例的主要内容,如果未能解决你的问题,请参考以下文章