您的位置:首页 > 理论基础 > 计算机网络

BOOST UDP 网络通信(1)

2017-07-15 20:07 218 查看
包含头文件

#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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: