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

被折叠的 条评论
为什么被折叠?



