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);
}

  

posted on 2016-03-04 15:42  itdef  阅读(521)  评论(0编辑  收藏  举报

导航