UDP boost::asio的实现
2012-11-29 10:40
218 查看
最近在研究网络相关的东西,发现之前对UDP的理解很弱,太依赖于TCP,依赖到甚至忘记了还有一个UDP的存在。于是在网上随便搜了UDP socket编程的相关代码和资料,发现有人写的编程例子里面居然还有connect的存在,我很无语。
UDP相对于TCP而言是不可靠的传输协议,在网络环境较差的情况下用TCP无疑是唯一的选择,在网络环境很好的情况下,比如局域网内部的消息传输,进程与进程之间的通信,UDP无疑是最好的选择,UDP不仅在传输效率上有很大的优势,我觉得更大的优势在于它不需要维护连接,可以减少很多逻辑上的冗余。
下面给大家看看一段代码,UDP的简单通信。
服务端代码,实现了echo功能:
client端,输入
本人对UDP的理解也很肤浅,有纰漏地方敬请指出,不甚感激。
UDP相对于TCP而言是不可靠的传输协议,在网络环境较差的情况下用TCP无疑是唯一的选择,在网络环境很好的情况下,比如局域网内部的消息传输,进程与进程之间的通信,UDP无疑是最好的选择,UDP不仅在传输效率上有很大的优势,我觉得更大的优势在于它不需要维护连接,可以减少很多逻辑上的冗余。
下面给大家看看一段代码,UDP的简单通信。
服务端代码,实现了echo功能:
/** @file UdpEchoServer.cpp * @note Hangzhou Hikvision System Technology Co., Ltd. All Rights Reserved. * @brief an udp server, echo what the client say. * * @author Zou Tuoyu * @date 2012/11/28 * * @note 历史记录: * @note V1.0.0.0 创建 */ //boost #include "boost/thread.hpp" #include "boost/asio.hpp" //stl #include <string> #include <iostream> using namespace std; int main() { boost::asio::io_service io_service; boost::asio::ip::udp::socket udp_socket(io_service); boost::asio::ip::udp::endpoint local_add(boost::asio::ip::address::from_string("10.64.49.70"), 7474); udp_socket.open(local_add.protocol()); udp_socket.bind(local_add); char receive_buffer[1024] = {0}; while (true) { boost::asio::ip::udp::endpoint send_point; udp_socket.receive_from(boost::asio::buffer(receive_buffer, 1024), send_point); cout << "recv:" << receive_buffer << endl; udp_socket.send_to(boost::asio::buffer(receive_buffer), send_point); memset(receive_buffer, 0, 1024); } return 1; }
client端,输入
//boost #include "boost/asio.hpp" //stl #include <iostream> using namespace std; int main() { boost::asio::io_service io_service; boost::asio::ip::udp::socket socket(io_service); boost::asio::ip::udp::endpoint end_point(boost::asio::ip::address::from_string("10.64.49.70"), 7474); socket.open(end_point.protocol()); char receive_buffer[1024] = {0}; while (true) { cout << "input:"; string input_data; cin >> input_data; cout << endl; try { socket.send_to(boost::asio::buffer(input_data.c_str(), input_data.size()), end_point); socket.receive_from(boost::asio::buffer(receive_buffer, 1024), end_point); cout << "recv:" << receive_buffer << endl; } catch (boost::system::system_error &e) { cout << "process failed:" << e.what() << endl; } } }
本人对UDP的理解也很肤浅,有纰漏地方敬请指出,不甚感激。
相关文章推荐
- UDP boost::asio的实现
- UDP boost::asio的实现
- boost::asio使用UDP协议通信源码实现
- Boost实现简单的udp代理服务器
- boost中的asio实现定时器功能
- 为何 Boost 的 Asio 要使用 Proactor 模式实现?
- C++03:使用Boost-用Asio实现简易Echo Server
- 关于boost::asio::async_write的实现机制
- Boost.Asio学习之实现广播ChatRoom
- boost的asio接收单路大数据量udp包的方法
- Boost::asio io_service 实现分析
- 高性能服务器开发之boost.asio实现原理
- 基于Boost::asio库的网络编程实现基础
- boost::asio 实现 libtorrent (zz)
- Boost::asio io_service 实现分析
- boost中asio网络库多线程并发处理实现,以及asio在多线程模型中线程的调度情况和线程安全。
- 利用boost::asio实现一个简单的服务器框架
- 【Boost】boost库asio详解9——UDP的简单例子1
- boost asio 异步实现tcp通讯
- boost asio 实现一个TCP服务端线程池