Boost.Asio C++ 网络编程之六:UDP回显客户端/服务

       因为UDP不能保证所有消息都抵达接收者,所以不能保证消息都以回车结尾。

       在服务端,收到消息后,简单的回发给客户端,并且不关闭socket,因为这是UDP。

一.UDP同步客户端

UDP客户端比TCP客户端要简单:

#ifdef WIN32
#define _WIN32_WINNT 0x0501
#include 
#endif

#include 
#include 
#include 
#include 
#include 
using namespace boost::asio;
io_service service;

ip::udp::endpoint ep(ip::address::from_string("127.0.0.1"), 8001);

void sync_echo(std::string msg) {
	ip::udp::socket sock(service, ip::udp::endpoint(ip::udp::v4(), 0));
	sock.send_to(buffer(msg), ep);
	char buff[1024];
	ip::udp::endpoint sender_ep;
	int bytes = sock.receive_from(buffer(buff), sender_ep);
	std::string copy(buff, bytes);
	std::cout << "server echoed our " << msg << ": "
		<< (copy == msg ? "OK" : "FAIL") << std::endl;
	sock.close();
}

int main(int argc, char* argv[]) {
	char* messages[] = { "Can", "ge", "ge" , "blog" , 0 };
	boost::thread_group threads;
	for (char ** message = messages; *message; ++message) {
		threads.create_thread(boost::bind(sync_echo, *message));
		boost::this_thread::sleep(boost::posix_time::millisec(100));
	}
	threads.join_all();
	system("pause");
}

二.UDP同步服务端
UDP服务端会是你写过的最简单的服务端:

#ifdef WIN32
#define _WIN32_WINNT 0x0501
#include 
#endif

#include 
#include 
#include 
#include 
using namespace boost::asio;
using namespace boost::posix_time;
io_service service;
void handle_connections() {
	char buff[1024];
	ip::udp::socket sock(service, ip::udp::endpoint(ip::udp::v4(), 8001));
	while (true) {
		ip::udp::endpoint sender_ep;
		int bytes = sock.receive_from(buffer(buff), sender_ep);
		std::string msg(buff, bytes);
		sock.send_to(buffer(msg), sender_ep);
	}
}

int main(int argc, char* argv[]) {
	handle_connections();
}
下面是客户端回显的结果,当然要先启动服务端。

Boost.Asio C++ 网络编程之六:UDP回显客户端/服务_第1张图片

三.UDP异步客户端

#ifdef WIN32  
#define _WIN32_WINNT 0x0501  
#include   
#endif  

#include   
#include   
#include   
#include   
#include   
using namespace boost::asio;
io_service service;
ip::udp::endpoint ep(ip::address::from_string("127.0.0.1"), 8001);


#define MEM_FN(x)       boost::bind(&self_type::x, shared_from_this())  
#define MEM_FN1(x,y)    boost::bind(&self_type::x, shared_from_this(),y)  
#define MEM_FN2(x,y,z)  boost::bind(&self_type::x, shared_from_this(),y,z)  


class talk_to_svr : public boost::enable_shared_from_this
	, boost::noncopyable {
	typedef talk_to_svr self_type;
	talk_to_svr(const std::string & message)
		: sock_(service, ip::udp::endpoint(ip::udp::v4(), 0)), started_(true), message_(message) {}
	void start() {
		do_write(message_);
	}
public:
	typedef boost::system::error_code error_code;
	typedef boost::shared_ptr ptr;


	static ptr start(const std::string & message) {
		ptr new_(new talk_to_svr(message));
		new_->start();
		return new_;
	}
	bool started() { return started_; }
private:
	void on_read(const error_code & err, size_t bytes) {
		if (!err) {
			std::string copy(read_buffer_, bytes);
			std::cout << "server echoed our " << message_ << ": "
				<< (copy == message_ ? "OK" : "FAIL") << std::endl;
		}
	}
	void on_write(const error_code & err, size_t bytes) {
		do_read();
	}
	void do_read() {
		sock_.async_receive_from(buffer(read_buffer_), sender_ep,
			MEM_FN2(on_read, _1, _2));
	}
	void do_write(const std::string & msg) {
		std::copy(msg.begin(), msg.end(), write_buffer_);
		sock_.async_send_to(buffer(write_buffer_, msg.size()), ep,
			MEM_FN2(on_write, _1, _2));
	}


private:
	ip::udp::socket sock_;
	ip::udp::endpoint sender_ep;
	enum { max_msg = 1024 };
	char read_buffer_[max_msg];
	char write_buffer_[max_msg];
	bool started_;
	std::string message_;
};


int main(int argc, char* argv[]) {
	char* messages[] = { "Can", "ge", "ge", "blog", 0 };
	for (char ** message = messages; *message; ++message) {
		talk_to_svr::start(*message);
		boost::this_thread::sleep(boost::posix_time::millisec(100));
	}
	service.run();
	system("pause");
}
四.UDP异步服务器
#ifdef WIN32
#define _WIN32_WINNT 0x0501
#include 
#endif

#include 
#include 
#include 
#include 
using namespace boost::asio;
using namespace boost::posix_time;
io_service service;

#define MEM_FN(x)       boost::bind(&self_type::x, shared_from_this())  
#define MEM_FN1(x,y)    boost::bind(&self_type::x, shared_from_this(),y)  
#define MEM_FN2(x,y,z)  boost::bind(&self_type::x, shared_from_this(),y,z)  

class talk_to_client : public boost::enable_shared_from_this, boost::noncopyable {
	typedef talk_to_client self_type;
	talk_to_client() : sock_(service, ip::udp::endpoint(ip::udp::v4(), 8001)), started_(false) {}
public:
	typedef boost::system::error_code error_code;
	typedef boost::shared_ptr ptr;

	void start() {
		started_ = true;
		do_read();
	}
	static ptr new_() {
		ptr new_(new talk_to_client);
		return new_;
	}
	ip::udp::socket & sock() { return sock_; }
private:
	void on_read(const error_code & err, size_t bytes) {
		if (!err) {
			std::string msg(read_buffer_, bytes);
			do_write(msg);
		}
	}

	void on_write(const error_code & err, size_t bytes) {
		do_read();
	}
	void do_read() {
		sock_.async_receive_from(buffer(read_buffer_), sender_ep,
			MEM_FN2(on_read, _1, _2));
	}
	void do_write(const std::string & msg) {
		std::copy(msg.begin(), msg.end(), write_buffer_);
		sock_.async_send_to(buffer(write_buffer_, msg.size()), sender_ep,
			MEM_FN2(on_write, _1, _2));
	}
	
private:
	ip::udp::socket sock_;
	ip::udp::endpoint sender_ep;
	enum { max_msg = 1024 };
	char read_buffer_[max_msg];
	char write_buffer_[max_msg];
	bool started_;
};

int main(int argc, char* argv[]) {
	talk_to_client::ptr client = talk_to_client::new_();
	client->start();
	service.run();
}
       客户端回显结果和同步时一样,如下:

Boost.Asio C++ 网络编程之六:UDP回显客户端/服务_第2张图片

参考链接:http://download.csdn.net/download/caoshangpa/10229882

你可能感兴趣的:(Boost.Asio,C++,网络编程,Asio,Boost,网络编程)