boost库在工作(37)网络UDP服务端之七

来源:互联网 发布:php商城分销系统源码 编辑:程序博客网 时间:2024/04/30 10:16

前面介绍的都是网络TCP的服务器和客户端,其实还有UDP的服务器和客户端,同时也有同步和异步之分。UDP与TCP最大的区别,就是TCP是基于连接的,而UDP是无连接的。这里所谓的连接是指对方中断服务时,另外一方是可以感知的,而UDP是无法感知对方是否中断服务。还有另外一点,TCP发送的数据包是有流量控制和顺序控制的,而UDP是无流量控制和顺序控制的。因而采用UDP时,基本上都是发送一些无关顺序,或者丢失的情况下使用。比如UDP使用在即时语音通讯、视频通讯上,就存在广泛的使用。由于语音通讯时,对于已经丢失的话,可以再说,并且过时的语音再播放出来也是无意义的。还有在视频会议上,由于不同的客户存在不同的带宽和处理速度,因此,对于不同的客户在视频上同步,也是通过慢速的客户进行丢掉数据处理的,否则慢速的客户会越来越多视频数据堆积,从而看不到新的视频。下面就来使用boost库来实现一个UDP服务器,并且它是基于同步的服务器。代码如下:

// boost_026.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <ctime>#include <boost/asio/ip/tcp.hpp>#include <boost/asio.hpp>#include <boost/bind.hpp>#include <boost/enable_shared_from_this.hpp>#include <boost/shared_ptr.hpp>#include <boost/array.hpp>#include <iostream>#include <string>//把当前时间转换为字符串。std::string make_daytime_string(){using namespace std; // For time_t, time and ctime;time_t now = time(0);return ctime(&now);}////创建一个UDP的时间服务器。//软件开发人员: 蔡军生  2013-08-11 //QQ: 9073204//void TestUdp(void){//定义一个IO服务。boost::asio::io_service io_service;//创建UDP的SOCKET,协议为V4版本,端口为13.boost::asio::ip::udp::socket socket(io_service, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 13));//循环处理所有客户端发送过来的命令。for (;;){boost::array<char, 1> recv_buf;boost::asio::ip::udp::endpoint remote_endpoint;boost::system::error_code error;//接收客户端数据。socket.receive_from(boost::asio::buffer(recv_buf),remote_endpoint, 0, error);//如果出错,就抛出异常。if (error && error != boost::asio::error::message_size){throw boost::system::system_error(error);}//获取当前时间字符串.std::string message = make_daytime_string();boost::system::error_code ignored_error;//把时间字符串发送给客户端。socket.send_to(boost::asio::buffer(message),remote_endpoint, 0, ignored_error);}}int _tmain(int argc, _TCHAR* argv[]){//TestUdp();return 0;}

原创粉丝点击