BOOST UDP 网络通信(1)

该博客介绍了如何利用BOOST库进行UDP网络通信的基础操作,包括服务器端和客户端的创建。通过包含<boos/asio.hpp>头文件,博主展示了如何建立UDP服务器和客户端的基本框架。

包含头文件

#include <boost/asio.hpp>

#include <iostream>

UDP服务器端:

int main( int argc, char * argv[] )
{
	boost::asio::io_service ios;

	//-------- Begin 1;
	boost::asio::ip::udp::socket sock( ios );
	boost::asio::ip::udp::endpoint ep( boost::asio::ip::address::from_string("127.0.0.1"), 6688 );

	//通过protocol()函数来确定sock到底支持哪种协议(TCP / UDP);无参时 内核自己决定使用哪一个;
	sock.open( ep.protocol() );  // 等价于 sock.open( boost::asio::ip::udp::v4() );

	sock.bind( ep );
	//++++++++ End 1;

	//-------- Begin 2 如下写法 可以 省略 sock.open / sock.bind 操作;
	//boost::asio::ip::udp::socket sock( ios, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 6688) );
	//++++++++ End 2;

	//接收数据buff;
	char receive_buff[1024] = {0};
	while( true )
	{
		try
		{
			//接收客户端连接进来的短点;
			boost::asio::ip::udp::endpoint send_point;

			//接收客户端发送的数据;
			sock.receive_from( boost::asio::buffer(receive_buff, 1024), send_point );
			std::cout << "Recv : " << receive_buff << std::endl;

			//将接受的数据再发送回去;
			sock.send_to( boost::asio::buffer(receive_buff), send_point );

			memset( receive_buff, 0, 1024 );

		}
		catch ( boost::system::system_error &e )
		{
			std::cout << "process failed : " << e.what() << std::endl;
		}
	}
}

UDP客户端:

int main( int argc, char * argv[] )
{
	boost::asio::io_service ios;
	//-------- Begin 1;
	boost::asio::ip::udp::socket sock( ios );
	//++++++++ End 1;

	//-------- Begin 2 如下写法 可以 省略 sock.open 操作;
	//boost::asio::ip::udp::socket sock( ios, boost::asio::ip::udp::v4() );
	//++++++++ End 2;

	boost::asio::ip::udp::endpoint ep( boost::asio::ip::address::from_string("127.0.0.1"), 6688 );

	//通过protocol()函数来确定sock到底支持哪种协议(TCP / UDP);无参时 内核自己决定使用哪一个;
	sock.open( ep.protocol() );  // 等价于 sock.open( boost::asio::ip::udp::v4() );

	//接收数据buff;
	char receive_buff[1024] = {0};

	while( true )
	{
		std::cout << "Input : ";

		//输入所要传输的数据;
		std::string input_data;
		std::cin >> input_data;
		std::cout << std::endl;

		try
		{
			//向服务端发送数据;
			sock.send_to( boost::asio::buffer(input_data.c_str(), input_data.size()), ep );

			//接收服务端发送的数据;
			sock.receive_from( boost::asio::buffer(receive_buff, 1024), ep );

			std::cout << "Receive : " << receive_buff << std::endl;
		}
		catch ( boost::system::system_error &e )
		{
			std::cout << "process failed : " << e.what() << std::endl;
		}
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值