asio学习之udp client

本文介绍了一个使用ASIO库进行同步和异步UDP通信的C++示例程序。同步部分展示了如何创建并绑定本地端点,向远程端点发送数据。异步部分则利用了自定义的asio_timer库,实现了周期性数据发送的功能。
摘要由CSDN通过智能技术生成

 

同步的:

 



#define ASIO_STANDALONE	
#define D_WIN32_WINNT  0x0501
#include <string>
#include <asio.hpp>
#include <iostream>

using namespace std;
using namespace asio;

int main(int argc, char* argv[])
{
	io_service my_io_service; // ip::udp::endpoint my_local_enpoint(ip::udp::v4(),0);/*another way to create endpoint*/
							  //   my_udp_socket.open(my_login_server_endpoint.protocol());  
							  //   my_udp_socket.bind(my_local_enpoint);

	ip::udp::endpoint local_endpoint(ip::udp::v4(), 7777); //create endpoint,this a local endpoint

	ip::udp::endpoint remote_endpoint(ip::address_v4::from_string("127.0.0.1"), 2300);//create a remote endpoint
																					  //don't  fill (ip::udp::v4()) in the first parameter,it will cause that the contents are sent out the failure!
	ip::udp::socket socket(my_io_service, local_endpoint);//create socket and bind the endpoint

	char *send_data = "hello! my name is Bojie. Can you see me?";/*the contents to be sent*/

	try
	{
		while (1)
		{
			Sleep(1000);
			socket.send_to(buffer(send_data, strlen(send_data) + 1/*the size of contents*/), remote_endpoint);
		}
	}
	catch (std::exception& e)//to get the error when sending
	{
		std::cerr << e.what() << std::endl;
	}

	return 0;
}

 

异步的:

异步程序引用了一个asio_timer,不是asio自带的,是从github上拿来的,功能是实现周期性的发送数据。


#define ASIO_STANDALONE	
#define _WIN32_WINNT  0x0601 



#include <cstdlib>
#include <iostream>
#include <memory>
#include <thread>
#include <ctime>
#include "asio.hpp"

#include "asio_timer.h"


using namespace std;


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


class noncopyable {
protected:
	constexpr noncopyable() = default;
	~noncopyable() = default;
	noncopyable(const noncopyable &) = delete;
	noncopyable &operator= (const noncopyable &) = delete;
};



class talk_to_svr : public enable_shared_from_this<talk_to_svr>, noncopyable
{

public:
	talk_to_svr(asio::io_service& io_context, const std::string & message)
		: sock_(io_context, asio::ip::udp::endpoint(asio::ip::udp::v4(), 0)), started_(true), message_(message) ,
		 timer_manager_(io_context)
	{
		timer_manager_.Add(this, 1, &talk_to_svr::Timer1Sec);
		timer_manager_.Run();
		start();
	}

	
	typedef shared_ptr<talk_to_svr> ptr;
	
	void start() {
		do_write(message_);
	}



	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 us " << copy << std::endl;
				//<< (copy == message_ ? "OK" : "FAIL") << std::endl;
		}
		start();
	}
	void on_write(const error_code & err, size_t bytes) {
		printf("client write result:%d, bytes:%d \n", err.value(), bytes);
		do_read();
	}
	void do_read() {
		sock_.async_receive_from(asio::buffer(read_buffer_), sender_ep,
		bind(&talk_to_svr::on_read,
			this,
			std::placeholders::_1,
			std::placeholders::_2));
	}
	void do_write(const std::string & msg) {
		std::copy(msg.begin(), msg.end(), write_buffer_);
		sock_.async_send_to(asio::buffer(write_buffer_, msg.size()), ep,
			bind(&talk_to_svr::on_write, 
				this,
				std::placeholders::_1, 
				std::placeholders::_2));
	}
	void Timer1Sec() {
		start();
		std::cout << "Timer1Sec." << std::endl;
	}

private:
	asiotimer::TimerManager<std::chrono::seconds> timer_manager_;

private:
	asio::ip::udp::socket sock_;
	asio::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[])
{
	
	asio::io_service io_service;
	talk_to_svr client(io_service,"hello");
	
	io_service.run();

	system("pause");
}

asio_timer.h     取自: https://github.com/chrisniael/asio-timer/src  实现周期性定时

#ifndef ASIO_TIMER_ASIO_TIMER_H_
#define ASIO_TIMER_ASIO_TIMER_H_

#include <chrono>
#include <functional>

#include "asio.hpp"
#include "asio/steady_timer.hpp"

namespace asiotimer {

template <typename TimeUnit>
class TimerManager {
 public:
  struct TimerItem {
    TimerItem(asio::io_service & io_service, int seconds,
              const std::function<void ()> & f) : timer(io_service),
                                                  duration(seconds),
                                                  func(f) {}
    asio::steady_timer timer;
    TimeUnit duration;
    std::function<void ()> func;
  };

  TimerManager(asio::io_service & io_service) : io_service_(io_service) {}
  TimerManager(TimerManager &) = delete;
  TimerManager & operator = (const TimerManager &) = delete;

  template <typename T>
  void Add(T * obj, const unsigned int & duration, void (T::* mem_func)()) {
    std::function<void ()> func = std::bind(mem_func, obj);
    this->items_.push_back(std::make_shared<TimerItem>(
                               this->io_service_,
                               duration,
                               func));
  }

  void Run() {
    for (auto & item : this->items_) {
      asio::steady_timer & timer = item->timer;
      const TimeUnit & duration = item->duration;
      const std::function<void ()> & func = item->func;
      TimerLoop(timer, duration, func);
    }
  }

 protected:
  void TimerLoop(asio::steady_timer & timer,
                 const TimeUnit & duration,
                 const std::function<void ()> & func) {
    timer.expires_from_now(duration);
    timer.async_wait(
        [this, &timer, duration, func] (const asio::error_code &) {
          func();
          TimerLoop(timer, duration, func);
        });
  }

 private:
  asio::io_service & io_service_;
  std::vector< std::shared_ptr<TimerItem> > items_;
};

}    // namespace asiotimer

#endif    // ASIO_TIMER_ASIO_TIMER_H_

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

路边闲人2

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值