asio學習之udp client

 

同步的:

 



#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_

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章