Ticket #9406: asio_error.cpp

File asio_error.cpp, 3.0 KB (added by icerlion@…, 9 years ago)

test code for this issue

Line 
1// asio_error.cpp : Defines the entry point for the console application.
2//
3
4#include "stdafx.h"
5#include "boost/bind.hpp"
6#include "boost/asio.hpp"
7
8class UDPServer
9{
10public:
11 UDPServer()
12 :m_socket(m_io_service),
13 m_timer(m_io_service)
14 {
15 }
16
17 virtual ~UDPServer()
18 {
19
20 }
21
22 void Initialize(const std::string& strIP, int nPort)
23 {
24 boost::system::error_code ec;
25 boost::asio::ip::address ad = boost::asio::ip::address::from_string(strIP, ec);
26 boost::asio::ip::udp::endpoint ep(ad, nPort);
27 m_socket.open(ep.protocol());
28 m_socket.bind(ep, ec);
29 {
30 // TEST CODE:
31 boost::asio::ip::udp::endpoint ep(boost::asio::ip::address::from_string("172.18.8.111", ec), 8001);
32 m_vServerGroup.push_back(ep);
33 }
34 }
35
36 void Start()
37 {
38 StartAsyncReceiveFrom();
39 NoticeSelfUp();
40 while (true)
41 {
42 boost::system::error_code ec;
43 m_io_service.poll(ec);
44 }
45 }
46
47 void SendUDPMsg(const char* pMsg, int nLen, boost::asio::ip::udp::endpoint& dest_ep)
48 {
49 m_socket.async_send_to(
50 boost::asio::buffer(pMsg, nLen),
51 dest_ep,
52 boost::bind(&UDPServer::HandleSendTo, this, _1, _2, boost::ref(dest_ep)));
53 }
54
55protected:
56 void NoticeSelfUp()
57 {
58 size_t count = m_vServerGroup.size();
59 char* pBuff = "this is up";
60 for (size_t i = 0; i < count; ++i)
61 {
62 SendUDPMsg(pBuff, strlen(pBuff), m_vServerGroup[i]);
63 }
64 m_timer.expires_from_now(boost::posix_time::seconds(5));
65 m_timer.async_wait(boost::bind(&UDPServer::NoticeSelfUp, this));
66 }
67
68 void HandleReceiveFrom(const boost::system::error_code& ec, size_t bytes_recvd)
69 {
70 if (ec)
71 {
72 std::cout<<"HandleReceiveFrom error: \t"<<ec<<std::endl;
73 }
74 else
75 {
76 // TODO
77 }
78 StartAsyncReceiveFrom();
79 }
80
81 void HandleSendTo(const boost::system::error_code& ec, size_t bytes_sent, boost::asio::ip::udp::endpoint& ep)
82 {
83 if (ec)
84 {
85 std::cout<<"HandleReceiveFrom error: \t"<<ec<<"\t"<<ep<<std::endl;
86 }
87 else
88 {
89 // TODO
90 }
91 }
92
93 void StartAsyncReceiveFrom()
94 {
95 m_socket.async_receive_from(boost::asio::buffer(m_buff, max_length),
96 m_sender_point,
97 boost::bind(&UDPServer::HandleReceiveFrom, this, _1, _2));
98 }
99
100private:
101 boost::asio::io_service m_io_service;
102 boost::asio::ip::udp::socket m_socket;
103 boost::asio::ip::udp::endpoint m_sender_point;
104 boost::asio::deadline_timer m_timer;
105 std::vector<boost::asio::ip::udp::endpoint> m_vServerGroup;
106 enum { max_length = 1024 };
107 char m_buff[max_length];
108};
109
110int _tmain(int argc, _TCHAR* argv[])
111{
112 UDPServer server;
113 server.Initialize("172.18.8.111", 8000);
114 server.Start();
115 return 0;
116}
117