您的位置:首页 > 其它

UDP boost::asio的实现

2012-11-29 10:40 218 查看
最近在研究网络相关的东西,发现之前对UDP的理解很弱,太依赖于TCP,依赖到甚至忘记了还有一个UDP的存在。于是在网上随便搜了UDP socket编程的相关代码和资料,发现有人写的编程例子里面居然还有connect的存在,我很无语。

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的理解也很肤浅,有纰漏地方敬请指出,不甚感激。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: