BOOST UDP 网络通信(1)
2017-07-15 20:07
218 查看
包含头文件
#include <boost/asio.hpp>
#include <iostream>
UDP服务器端:
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; } } }
相关文章推荐
- BOOST UDP 网络通信(2) --如何传输结构体
- 用java编写简单UDP网络通信程序
- Java系列讲座二:Socket网络通信实现聊天软件项目讲解(UDP)
- Java网络编程之UDP网络通信
- 在linux网络UDP通信中,关于客户端是否绑定的理解
- 【java面试系列之网络编程】TCP和UDP的区别、TCP协议的三次握手和四次挥手、TCP协议的通信状态、网络编程时的同步、异步、阻塞、非阻塞、进程间的通信方式、TCP的流量控制和拥塞控制
- Java学习系列(十八)Java面向对象之基于UDP协议的网络通信
- c#网络通信框架networkcomms内核解析之十一 TCP连接与UDP连接
- (转) 在linux网络UDP通信中,关于客户端是否绑定的理解
- [python] 专题七.网络编程之套接字Socket、TCP和UDP通信实例
- [Linux网络编程]UDP编程--UDP通信程序服务器端
- Socket网络通信理论基础搜集(TCP/IP协议栈与数据包封装+TCP与UDP的区别)
- 一个简单的JAVA网络通信 UDP 单工方式
- 网络通信协议-UDP
- Java网络编程四 非阻塞通信UDP
- Java中网络通信编程之UDP通信
- 【Java网络编程】基于 UDP 的聊天通信
- Java基础—网络编程【OSI/RM TCP/IP】【网络通信三要素】【UDP传输 & TCP传输】【DNS域名解析】
- 网络编程【OSI/RM TCP/IP】【网络通信三要素】【UDP传输 & TCP传输】【DNS域名解析】
- 13.进程间通信---网络通信(TCP协议和UDP协议的比较)