C++ Boost::Asio

Asio

Boost.Asio 是一个跨平台的C++库,用于网络和底层I/O编程,它使用现代C++方法为开发人员提供一致的异步模型。

  • 库学习建议

    核心概念优先级:

    1. io_context + 异步操作模型 ✓
    2. TCP/UDP编程基础 ✓
    3. 异步回调与completion handler ✓
    4. 定时器与deadline_timer ✓
    5. 简单的异步链 ✓

    可暂缓的内容:

    • 复杂的proactor模式理论
    • 所有高级特性(如协程支持)
    • 性能优化细节

定时器

通过展示如何对定时器执行阻塞来介绍 asio
所有的 asio 类都可以通过简单的包含 <boost/asio.hpp> 头文件来使用

Timer 1

所有使用 asio 的程序都需要 至少有一个 I/O 执行上下文 ,例如 io_contex 或 thread_pool 对象。I/O 执行上下文提供对 I/O 功能的访问。

1
2
3
4
5
6
7
8
9
10
void test1()
{
boost::asio::io_context io;

boost::asio::steady_timer timer(io, boost::asio::chrono::milliseconds(2700));

timer.wait();

std::cout << "Hello World!\n";
}

我们首先在函数的开头声明一个 io_context 类型的对象。

接下来的 boost::asio::steady_timer 类型的对象。提供 I/O 功能的和兴 asio 类总是接受一个执行器,或者对执行上下文的引用(如 io_context),作为它们的第一个构造函数参数。构造函数的第二个参数将定时器设置为从现在起 2700 毫秒后到期。

以上示例中,对定时器执行 阻塞等待 。即,对 steady_timer::wait() 的调用将不会返回,直到定时器过期。定时器始终处于两种状态之一: 已过期 或 未过期 。如果在已过期的定时器上调用 steady_timer::wait() 函数,他将立即返回。

Timer 2

使用 asio 的异步功能意味着提供一个 完成令牌 。它决定了当 异步操作 完成时,结果将如何传递给 完成处理程序 。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void print(const boost::system::error_code& e)
{
std::cout << "Hello World." << std::endl;
}

void test2()
{
boost::asio::io_context io;

boost::asio::steady_timer timer(io, boost::asio::chrono::milliseconds(3500));

timer.async_wait(&print);

io.run();
}

调用 steady_timer::async_wait() 函数来执行异步等待。在调用函数时,我们传递上面定义的 print 函数。

最后,必须在 io_context 对象上调用 boost::asio::io_context::run() 成员函数。asio 库保证完成处理程序只会被当前正在调用 boost::asio::io_context::run() 的线程调用。因此,除非调用 boost::asio::io_context::run() 函数,否则异步等待完成的完成处理程序将 永远不会 被调用。

boost::aiso::io_context::run() 函数也会在还有 任务 时继续运行。

在本例中,任务是对定时器的异步等待,因此该调用将不会返回,直到定时器过期并且完成处理程序已返回。

io.run() 实际上是启动该异步上下文对象的事件循环。

Timer 3

要使用 asio 实现重复定时器,需要在完成处理程序中更改的定时器的到期时间,然后启动新的异步等待。完成处理程序需要能够访问定时器对象。为此可以向 print 函数添加两个新参数。

  • 一个指向定时器对象的指针
  • 一个计数器,以便在合适时停止程序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
void print_v2(const boost::system::error_code& e, boost::asio::steady_timer* t, int* count)
{
if (*count < 5)
{
std::cout << *count << std::endl;
++(*count);
t->expires_at(t->expiry() + boost::asio::chrono::seconds(1));
t->async_wait(std::bind(print_v2,
boost::asio::placeholders::error, t, count));
}
}

void test3()
{
boost::asio::io_context io;

int count = 0;

boost::asio::steady_timer timer(io, boost::asio::chrono::milliseconds(1500));

timer.async_wait(std::bind(print_v2,
boost::asio::placeholders::error, &timer, &count));

io.run();

std::cout << "Final count is " << count << std::endl;
}

print_v2 中,没有显示调用来要求 io_context 停止。其中(io.run()的返回值为 定时器被触发的次数 )关于 t→expires_at(t→expiry() + boost::asio::chrono::seconds(1)) 的调用,是调整定时器的到期时间前移一秒,通过相对于旧的到期时间计算新的到期时间。

然后启动一个新的异步等待定时器。 std::bind函数用于将额外的参数与完成处理程序关联。 steady_timer::async_wait() 函数期望一个具有 void(const boost::siystem::error_code&) 签名的处理函数。

绑定额外的参数将会将 print_v2 函数 转换 为与签名正确匹配的函数对象。

本例中, std::bind 的 boost::asio::placeholders::error 参数是传递给处理程序的错误对象的命名占位符。当启动异步操作时,如果使用 std::bind 必须仅指定与处理程序的参数列表匹配的参数。

Timer 4

可以使用成员函数作为完成处理函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class printer
{
private:
boost::asio::steady_timer timer_;
int count_;

public:
printer(boost::asio::io_context& io)
: timer_(io, boost::asio::chrono::seconds(1)), count_(0)
{
timer_.async_wait(std::bind(&printer::print, this));
}

~printer()
{
std::cout << "Final count is " << this->count_ << std::endl;
}

public:
void print()
{
if (count_ < 5)
{
std::cout << this->count_ << std::endl;
++this->count_;

timer_.expires_at(timer_.expiry() + boost::asio::chrono::seconds(1));
timer_.async_wait(std::bind(&printer::print, this));
}
}
};

void test5()
{
boost::asio::io_context io;
printer prntr(io);
io.run();
}

Timer 5

可以使用 strand 类模板在多线程程序中同步完成处理程序。

asio库保证完成处理程序仅会从当前正在调用 boost::asio::io_context::run() 的线程中调用。因此,仅从一个线程调用 boost::asio::io_context::run() 可以确保完成处理程序不会并发运行。

单线程方法通常是开始开发使用 asio 的应用程序的最佳选择。缺点是它对程序,特别是服务器的限制:

  • 当处理程序可能需要很长时间才能完成时,响应性差
  • 无法在多处理器系统上扩展。

为了突破这些限制,可以使用线程池进行 boost::asio::io_context::run() 的调用。但是,由于允许处理程序并发执行,当处理程序可能访问共享的线程不安全资源时,需要一种同步方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class printer
{
private:
boost::asio::strand<boost::asio::io_context::executor_type> strand_;
boost::asio::steady_timer timer1_;
boost::asio::steady_timer timer2_;
int count_;

public:
printer(boost::asio::io_context& io)
: strand_(boost::asio::make_strand(io)),
timer1_(io, boost::asio::chrono::milliseconds(1000)),
timer2_(io, boost::asio::chrono::milliseconds(1000)),
count_(0)
{
timer1_.async_wait(boost::asio::bind_executor(strand_,
std::bind(&printer::print1, this))
);
timer2_.async_wait(boost::asio::bind_executor(strand_,
std::bind(&printer::print2, this))
);
}

~printer()
{
std::cout << "Final count is " << count_ << std::endl;
}

public:
void print1()
{
if (count_ < 10)
{
std::cout << "Timer 1 " << count_ << "\t" << boost::this_thread::get_id() << std::endl;
++count_;

timer1_.expires_at(timer1_.expiry() + boost::asio::chrono::milliseconds(1000));
timer1_.async_wait(boost::asio::bind_executor(strand_,
std::bind(&printer::print1, this))
);
}
}

void print2()
{
if (count_ < 10)
{
std::cout << "Timer 2 " << count_ << "\t" << boost::this_thread::get_id() << std::endl;
++count_;

timer2_.expires_at(timer2_.expiry() + boost::asio::chrono::milliseconds(1000));
timer2_.async_wait(boost::asio::bind_executor(strand_,
std::bind(&printer::print2, this))
);
}
}
};

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void test1()
{
boost::asio::io_context io;
printer prtr(io);

boost::thread thrd(
[&io]() -> void {
io.run();
});

io.run();

std::cout << "Main Thread io.run() is worked out.\n";

thrd.join();
}

其中 strand 类模板时一个执行器适配器,它保证对于通过它调度的处理程序,一个正在执行的处理程序将被允许在下一个处理程序开始前完成。无论有多少线程正在调用 boost::asio::io_context::run() ,这都得到保证。

处理程序仍然可以与未通过 strand 调度的其他处理程序,或通过不同的 strand 对象调度的处理程序并发执行。

当启动异步操作时,每个完成处理程序都 “绑定” 到一个 boost::asio::strandboost::asio::io_context::executor_type 对象。 boost::asio::bind_ex返回一个新的处理程序,该处理程序会自动通过 strand 对下给你调度其包含的处理程序。通过将处理程序绑定到同一个 strand 可以确保不会 并发 执行。ecutor() 函数

在多线程程序中,如果异步操作的处理程序访问共享资源,则应同步这些处理程序。(本程序中,print1 print2 使用的共享资源是 std::count 和 count_ 数组成员。

以上的用例中,在子线程与主线程分别调用了 boost::asio::io_context::run() ,此时,主线程并不会立即退出,而是会等待异步操作的完成。

在此例中,我们知道主线程的 io.run() 会阻塞,所以在程序线程的最后才会输出 “Main Thread io.run() is worked.” 的提示。

本例中,两次 io.run() 的调用:

  1. 两个线程 共享 同一个 boost::asio::io_context 对象
  2. 两个线程 共同处理所有的异步操作
  3. boost::strand 的作用是确保 线程安全

TCP/UDP的同步-异步处理

同步TCP客户端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
#include <ctime>
#include <array>
#include <string>
#include <boost/asio.hpp>

namespace asio = boost::asio;

const int PORT = 8013;

int main(int argc, char *argv[])
{
using boost::asio::ip::tcp;
try
{
if(argc != 2) {
std::cerr << "Usage: client <host.ip>" << std::endl;
return 1;
}
// 创建异步上下文对象
boost::asio::io_context io_context;

// 将TCP通信端点resolver对象与异步上下文绑定
tcp::resolver resolver(io_context);
// TCP通信端点向(HOST.IP:PORT)服务器IP:PORT获取服务
// 若未经过配置 "daytime" 将默认映射到 13号端口
tcp::resolver::results_type endpoints = resolver.resolve(argv[1], std::to_string(PORT));

// 套接字对象绑定至异步上下文
tcp::socket socket(io_context);
// 异步上下文绑定至通信端点
boost::asio::connect(socket, endpoints);
while(true)
{
std::array<char, 128> buf;
boost::system::error_code error;

// 截取字节流大小
size_t len = socket.read_some(boost::asio::buffer(buf), error);

// 字节流结尾,接收完成
if(error == boost::asio::error::eof)
{
break;
}
else if(error)
{
throw boost::system::system_error(error);
}

// 输出的字符流
if(len > 0)
{
std::cout.write(buf.data(), len);
}

}
}
catch(std::exception& e) {
std::cerr << e.what() << std::endl;
}
return 0;
}

tcp::socket 可以创建一个套接字,使用 boost::asio::connect() 函数自动进行端点列表的连接。

boost::asio::buffer() 函数会自动确定数组的大小,可以防止缓冲区溢出。可以传入 std::array char[] std::vector 。

当服务器关闭连接时, ip::tcp::socket::read_some() 函数将以 boost::asio::error::eof 错误退出。

同步TCP服务端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <array>
#include <string>
#include <boost/asio.hpp>

using boost::asio::ip::tcp;
std::string make_daytime_string() {
std::time_t now = std::time(nullptr);
std::string res = std::ctime(&now);
return res;
}

int main()
{
try
{
// 创建异步上下文对象
boost::asio::io_context io_context;

// 指定使用的运输层协议(注意:Linux环境中1024以下的端口为特权端口)
tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), 8013));

// 无限循环,监听端口
while(true)
{
// 创建套接字对象,与异步上下文链接
tcp::socket socket(io_context);
// 将套接字与运输层相连(套接字作为运输层与应用层间的传输接口)
acceptor.accept(socket);
// 发送的消息实体 message
std::string message = make_daytime_string();
// 错误码
boost::system::error_code ignored_error;
// 异步上下文写入消息实体 message 并发出
boost::asio::write(socket, boost::asio::buffer(message), ignored_error);
}
}
catch(std::exception& e)
{
std::cerr << e.what() << '\n';
}
return 0;
}

通过创建一个 ip::tcp::acceptor 对象来监听新的连接。用于 ipv4 在 13 端口进行监听。

异步TCP服务端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#include <iostream>
#include <memory>
#include <functional>
#include <array>
#include <string>
#include <boost/asio.hpp>

using boost::asio::ip::tcp;

std::string make_daytime_string() {
std::time_t now = std::time(nullptr);
std::string res = std::ctime(&now);
return res;
}

// tcp连接类,继承自 std::enable_shared_from_this<tcp_connection>
// 提供了一个更安全的获取对象自身指针引用的方法
// 将业务逻辑 make_daytime_string 硬编码在该对象中
//
// tcp连接 以及 套接字接口 (运输层 + 套接字)
class tcp_connection
: public std::enable_shared_from_this<tcp_connection>
{
public:
using pointer = std::shared_ptr<tcp_connection>;
private:

tcp::socket socket_;
std::string message_;

private:
tcp_connection(boost::asio::io_context &io_context)
: socket_(io_context)
{ }

void handle_write(const boost::system::error_code &ec, size_t len)
{ }

public:
static pointer create(boost::asio::io_context &io_context)
{
// 通过shared_ptr将该tcp连接对象引出
return pointer(new tcp_connection(io_context));
}

// 引用该tcp连接的套接字对象
tcp::socket &socket()
{
return socket_;
}

// 打开连接,发送字节流
void start()
{
// 返回的响应字节流
message_ = make_daytime_string();
// 异步输出字节流
// 使用该tcp连接的套接字
// 传输的字节流
boost::asio::async_write(socket_, boost::asio::buffer(message_),
// 获取指向自身的shared_ptr指针引用
// 包装 handle_write() 方法,对字节流输出进行处理
[self = shared_from_this()]
(const boost::system::error_code &error, std::size_t bytes_transferred) {
self->handle_write(error, bytes_transferred);
}
);
}
};

// 服务器主机(服务器进程)(应用层处理)
class tcp_server
{
public:
tcp_server(boost::asio::io_context &io_context)
: io_context_(io_context),
acceptor_(io_context, tcp::endpoint(tcp::v4(), 8013))
{
// 打开服务器 start server
start_accept();
}

private:
boost::asio::io_context &io_context_;
tcp::acceptor acceptor_;

// 接受完成事件
void handle_accept(tcp_connection::pointer new_connection, const boost::system::error_code &error)
{
// 无错误,则建立一个新tcp连接
if(!error)
{
// 发送
new_connection->start();
}

// 发起一次异步接收操作,等待客户端连接
start_accept();
}

// 发起一次异步接收操作,等待客户端连接
void start_accept()
{
// 建立新连接 发送数据
tcp_connection::pointer new_connection = tcp_connection::create(io_context_);

// 处理接受连接,(handle_accept中的start发送数据至指定tcp连接的套接字接口)
acceptor_.async_accept(new_connection->socket(),
[this, new_connection]
(const boost::system::error_code &error) {
this->handle_accept(new_connection, error);
}
);
}
};

int main(int argc, char *argv[])
{
try
{
boost::asio::io_context io_context;
tcp_server server(io_context);
io_context.run();
}
catch(std::exception &e)
{
std::cerr << e.what() << '\n';
}

return 0;
}

UDP客户端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <array>
#include <iostream>
#include <boost/asio.hpp>

using boost::asio::ip::udp;

const int PORT = 8031;

int main(int argc, char* argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: client <host>" << std::endl;
return 1;
}

// 实例化异步上下文
boost::asio::io_context io_context;

// 将接收的响应绑定至 异步上下文
udp::resolver resolver(io_context);
// 端系统对象
udp::endpoint receiver_endpoint =
*resolver.resolve(udp::v4(), argv[1], std::to_string(PORT)).begin();

// 将套接字接口绑定至 异步上下文
udp::socket socket(io_context);
// 打开套接字接口
socket.open(udp::v4());

std::array<char, 1> send_buf = {{ 0 }};
// 向服务器发送请求
socket.send_to(boost::asio::buffer(send_buf), receiver_endpoint);

std::array<char, 128> recv_buf;
udp::endpoint sender_endpoint;

size_t len = socket.receive_from(
boost::asio::buffer(recv_buf), sender_endpoint);

// 输出接收到字节流
std::cout.write(recv_buf.data(), len);

}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}

return 0;
}

异步TCP-UDP服务端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#include <iostream>
#include <array>
#include <functional>
#include <memory>
#include <string>
#include <boost/asio.hpp>

using boost::asio::ip::tcp;
using boost::asio::ip::udp;

const int TCP_PORT = 8013;
const int UDP_PORT = 8031;

/**
* tcp::acceptor 处理连接的建立,为通过socket进行字节流的传输提供基础
* udp::resolver 进行域名与IP地址的转换,需要进行配置
*/

std::string make_daytime_string()
{
std::time_t now = std::time(nullptr);
std::string res = std::ctime(&now);
return res;
}

// tcp连接类
class tcp_connection
: public std::enable_shared_from_this<tcp_connection>
{
public:
typedef std::shared_ptr<tcp_connection> pointer;

// 建立tcp连接
static pointer create(boost::asio::io_context& io_context)
{
return pointer(new tcp_connection(io_context));
}

// 该tcp连接使用的套接字
tcp::socket& socket()
{
return socket_;
}

// 开始建立连接
void start()
{
// 运行服务
message_ = make_daytime_string();

// 异步发送提供的服务内容
boost::asio::async_write(socket_, boost::asio::buffer(message_),
[self = shared_from_this()]
(const boost::system::error_code &error, std::size_t bytes_transferred) {
// 处理发送的字节流
self->handle_write();
});
}

private:
tcp_connection(boost::asio::io_context& io_context)
: socket_(io_context)
{ }

void handle_write()
{ }

tcp::socket socket_; // 该TCP连接使用的套接字接口
std::string message_; // 发送的字节流
};

// tcp服务器
class tcp_server
{
public:
tcp_server(boost::asio::io_context& io_context)
: io_context_(io_context),
acceptor_(io_context, tcp::endpoint(tcp::v4(), TCP_PORT))
{
// 开始接收连接请求
start_accept();
}

private:
void start_accept()
{
// 创建一个新的tcp连接
tcp_connection::pointer new_connection =
tcp_connection::create(io_context_);

// 异步的接收从监听接口传来的连接请求
acceptor_.async_accept(new_connection->socket(),
[this, new_connection]
(const boost::system::error_code &error) {
// 处理连接请求并在new_connection上建立tcp连接
this->handle_accept(new_connection, error);
});
}

void handle_accept(tcp_connection::pointer new_connection,
const boost::system::error_code& error)
{
if (!error)
{
// 连接开始(业务开始)
new_connection->start();
}

// 再开始监听连接请求
start_accept();
}

boost::asio::io_context& io_context_; // 异步上下文
tcp::acceptor acceptor_; // 接收客户端系统
};

// udp服务器
class udp_server
{
public:
udp_server(boost::asio::io_context& io_context)
: socket_(io_context, udp::endpoint(udp::v4(), UDP_PORT))
{
// 开始接收请求
start_receive();
}

private:
void start_receive()
{
// 异步的从 客户端系统接收请求字节流
socket_.async_receive_from(boost::asio::buffer(recv_buffer_), remote_endpoint_,
[this]
(const boost::system::error_code &error, std::size_t bytes_transferred) {
// 处理接收到的字节流
this->handle_receive(error);
});
}

// 处理接收到的字节流
void handle_receive(const boost::system::error_code& error)
{
if (!error)
{
// 准备服务功能
std::shared_ptr<std::string> message(
new std::string(make_daytime_string())
);

// 向客户端系统,异步发送服务字节流
socket_.async_send_to(boost::asio::buffer(*message), remote_endpoint_,
[this, message]
(const boost::system::error_code &error, std::size_t bytes_transferred) {
// 处理发送的字节流
this->handle_send(message);
});

// 重新开始接收请求
start_receive();
}
}

void handle_send(std::shared_ptr<std::string> /*message*/)
{ }

udp::socket socket_; // 套接字接口
udp::endpoint remote_endpoint_; // 客户端系统
std::array<char, 1> recv_buffer_; // 接收到的字节流
};

int main(int argc, char *argv[])
{
try
{
// tcp udp 服务器使用同一个异步上下文
boost::asio::io_context io_context;
tcp_server server1(io_context);
udp_server server2(io_context);
io_context.run();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}

return 0;
}

Reference

  • boost::asio::io_context

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    void test2()
    {
    boost::asio::io_context io;
    std::vector<boost::asio::steady_timer> timers;

    const size_t N = 5;
    size_t t_ms = 1000; // 1000ms

    for (size_t i = 0; i < N; ++i)
    {
    std::string str = "Hello World.";
    boost::asio::steady_timer t(io, boost::asio::chrono::milliseconds(t_ms));
    t.async_wait(std::bind([i](const boost::system::error_code& ec, const std::string msg, const size_t tms) -> void {
    std::cout << "num " << i << "\t" << msg << "\r\n\t After Running " << tms << "ms\r\n" << std::endl;
    },
    boost::asio::placeholders::error, str, t_ms)
    );
    timers.emplace_back(boost::move(t));
    t_ms += 500; // self add 1000ms
    }

    std::cout << "Start async timer running.\n" << std::endl;

    // io.run();

    // io.run_one();
    // io.run_one();

    // io.run_for(boost::asio::chrono::milliseconds(1300));

    // io.run_until(boost::asio::chrono::system_clock::now() + boost::asio::chrono::milliseconds(1300));

    //io.run_one();
    //io.stop();
    //io.run_one(); // cannt run
    //if (io.stopped())
    //{
    // std::cout << "io_context object had been stopped.\n" << std::endl;
    //}
    //io.run(); // cannt run
    //io.restart(); // restart the event loop for async tasks running
    //io.run_one();

    //boost::this_thread::sleep_for(boost::chrono::milliseconds(3500));
    // // io.poll();
    //for (size_t i = 0; i < N; ++i)
    //{
    // io.poll_one();
    //}

    std::cout << "Done all the timer tasks.\n" << std::endl;

    }

    执行器使用方法,代替了直接使用 boost::io_context引用 的模式,可以安全的从任何线程向一个上下文安全的投递任务。

    执行器(Executor)抽象了如何调度函数对象(任务事件)执行的机制。允许程序的任何位置、任何执行周期中,安全的向其所属的异步上下文注册事件处理程序。(是一个轻量级的“注册令牌”)廉价的复制对象、不拥有资源,上下文无关,时间无关,类型安全,生命周期安全。

    执行器是io_context的轻量级代理,它提供了一种类型安全、线程安全且与生命周期解耦的方式,允许在程序的任何执行阶段和任何执行上下文中,向其所属的异步事件循环注册事件处理程序。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    void test3()
    {
    boost::asio::io_context io;

    boost::asio::executor excu = io.get_executor();

    boost::asio::post(excu, []() -> void {
    std::cout << "This is a lambda in executor::post.\n" << std::endl;
    });

    boost::asio::dispatch(excu, []() -> void {
    std::cout << "This is a lambda in executor::dispatch.\n" << std::endl;
    });

    boost::asio::defer(excu, []() -> void {
    std::cout << "This is a lambda in executor::defer.\n" << std::endl;
    });

    io.run();
    }
  • boost::steady_timer

    不只是可以直接关联一个异步上下文,还可以关联一个关于上下文的执行器,更加灵活

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    void test4()
    {
    boost::asio::io_context io;

    boost::asio::any_io_executor excu = io.get_executor();

    boost::asio::post(excu, []() -> void {
    std::cout << "io_executor post this lambda func.\n" << std::endl;
    });

    boost::asio::steady_timer st(excu, boost::asio::chrono::milliseconds(1500));

    st.expires_at(st.expiry() - boost::asio::chrono::milliseconds(1300)); // 1500(-运行到此语句所花费的时间) - 1300

    st.async_wait([](const boost::system::error_code& ec) -> void {
    std::cout << "This steady_timer is binding on io_context::executor.\n";
    std::cout << "error code: " << ec.message() << std::endl;
    });

    st.async_wait([](const boost::system::error_code& ec) -> void {
    std::cout << "This steady_timer is binding on io_context::executor 2nd.\n";
    std::cout << "error code: " << ec.message() << std::endl;
    });

    st.async_wait([](const boost::system::error_code& ec) -> void {
    std::cout << "This steady_timer is binding on io_context::executor 3rd.\n";
    std::cout << "error code: " << ec.message() << std::endl;
    });

    boost::asio::post(st.get_executor(), []() -> void {
    std::cout << "steady_timer::get_executor() post this lambda func 2nd.\n" << std::endl;
    });

    // st.cancel();
    st.cancel_one();

    io.run();
    }

  • 关于网络

    • udp_server & udp_client

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      63
      64
      65
      class udp_server
      {
      using udp = boost::asio::ip::udp;
      private:
      udp::socket socket;
      udp::endpoint remote_endpoint;
      std::array<char, 1> rcv_buf;

      private:
      void start_receive()
      {
      socket.async_receive_from(
      boost::asio::buffer(rcv_buf), remote_endpoint,
      std::bind(
      &udp_server::recv_handler, this,
      boost::asio::placeholders::error,
      boost::asio::placeholders::bytes_transferred
      )
      );
      }

      void recv_handler(const boost::system::error_code& ec, size_t s)
      {
      try
      {
      if (!ec)
      {
      std::shared_ptr<std::string> message(new std::string("A Test Msg.\n"));

      socket.async_send_to(
      boost::asio::buffer(*message),
      remote_endpoint,
      std::bind(
      &udp_server::send_handler, this,
      message,
      boost::asio::placeholders::error
      )
      );
      }
      else
      {
      std::cout << ec.message() << std::endl;
      return;
      }
      }
      catch (const std::exception& e)
      {
      std::cout << e.what() << std::endl;
      }

      start_receive();
      }

      void send_handler(std::shared_ptr<std::string> msg, const boost::system::error_code& ec)
      {

      }

      public:
      udp_server(boost::asio::io_context& io)
      : socket(io, udp::endpoint(udp::v4(), 6969))
      {
      start_receive();
      }
      };
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61

      void udp_server_test()
      {
      try
      {
      boost::asio::io_context io;
      udp_server server(io);
      io.run();
      }
      catch (const std::exception& ec)
      {
      std::cout << ec.what() << std::endl;
      }
      }

      void udp_client_test()
      {
      using boost::asio::ip::udp;

      try
      {
      boost::asio::io_context io;
      boost::asio::any_io_executor io_excu(io.get_executor());

      udp::resolver rsovr(io_excu);
      udp::endpoint rcv_endpoint = *rsovr.resolve(udp::v4(), "127.0.0.1", "6969").begin();

      udp::socket udp_sokt(io_excu);
      udp_sokt.open(udp::v4());

      std::array<char, 1> snd_buf({ {0} });
      udp_sokt.send_to(boost::asio::buffer(snd_buf), rcv_endpoint);

      std::array<char, 128> rcv_buf;
      udp::endpoint snd_endpoint;
      size_t len = udp_sokt.receive_from(boost::asio::buffer(rcv_buf), snd_endpoint);

      std::cout << "client get " << std::endl;
      std::cout.write(rcv_buf.data(), len);
      }
      catch(const std::exception& e)
      {
      std::cout << "udp_client_test error.\n" << std::endl;
      std::cout << e.what() << std::endl;
      }
      }

      void udp_test()
      {
      boost::thread_group thrds;

      thrds.add_thread(new boost::thread(udp_server_test));
      boost::this_thread::sleep_for(boost::chrono::milliseconds(1000));
      for (int i = 0; i < 5; ++i)
      {
      thrds.add_thread(new boost::thread(udp_client_test));
      }

      thrds.join_all();
      }

    • tcp_server & tcp_client

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      63
      64
      65
      66
      67
      68
      69
      70
      71
      72
      73
      74
      75
      76
      77
      78
      79
      80
      81
      82
      83
      84
      85
      86
      87
      class tcp_connection
      : public std::enable_shared_from_this<tcp_connection>
      {
      using tcp = boost::asio::ip::tcp;
      private:
      tcp::socket socket_;
      std::string message_;

      private:
      tcp_connection(boost::asio::io_context& io_context)
      : socket_(io_context)
      {
      }

      void handle_write(const boost::system::error_code& /*error*/,
      size_t /*bytes_transferred*/)
      {
      }

      public:
      using pointer = std::shared_ptr<tcp_connection>;

      static pointer create(boost::asio::io_context& io_context)
      {
      return pointer(new tcp_connection(io_context));
      }

      tcp::socket& socket()
      {
      return socket_;
      }

      void start()
      {
      message_ = "A Simple Msg.";

      boost::asio::async_write(socket_, boost::asio::buffer(message_),
      std::bind(&tcp_connection::handle_write, shared_from_this(),
      boost::asio::placeholders::error,
      boost::asio::placeholders::bytes_transferred
      )
      );
      }

      };

      class tcp_server
      {
      using tcp = boost::asio::ip::tcp;
      private:
      boost::asio::io_context& io_context_;
      tcp::acceptor acceptor_;

      private:
      void start_accept()
      {
      tcp_connection::pointer new_connection = tcp_connection::create(io_context_);

      acceptor_.async_accept(new_connection->socket(),
      std::bind(&tcp_server::handle_accept, this, new_connection,
      boost::asio::placeholders::error
      )
      );
      }

      void handle_accept(tcp_connection::pointer new_connection,
      const boost::system::error_code& error)
      {
      if (!error)
      {
      new_connection->start();
      }

      start_accept();
      }

      public:
      // constructor
      tcp_server(boost::asio::io_context& io_context)
      : io_context_(io_context),
      acceptor_(io_context, tcp::endpoint(tcp::v4(), 6969))
      {
      start_accept();
      }

      };

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      63
      64
      65
      66
      67
      68
      void tcp_server_test()
      {
      try
      {
      boost::asio::io_context io;
      tcp_server server(io);
      io.run();
      }
      catch (const std::exception& e)
      {
      std::cout << e.what() << std::endl;
      }
      }

      void tcp_client_test()
      {
      using boost::asio::ip::tcp;

      try
      {
      boost::asio::io_context io;
      tcp::resolver resolver(io);

      tcp::resolver::results_type endpoints = resolver.resolve("127.0.0.1", "6969");
      tcp::socket socket(io);

      boost::asio::connect(socket, endpoints);

      for (;;)
      {
      std::array<char, 128> buf;
      boost::system::error_code err;

      size_t len = socket.read_some(boost::asio::buffer(buf), err);
      if (err == boost::asio::error::eof)
      {
      break;
      }
      else
      {
      throw boost::system::error_code(err);
      }

      std::cout << "get the massage." << std::endl;
      std::cout.write(buf.data(), len);
      }
      }
      catch (const std::exception& e)
      {
      std::cout << e.what() << std::endl;
      }
      }

      void tcp_test()
      {

      boost::thread_group thrds;

      thrds.add_thread(new boost::thread(tcp_server_test));

      boost::this_thread::sleep_for(boost::chrono::milliseconds(1000));

      thrds.add_thread(new boost::thread(tcp_client_test));

      thrds.join_all();

      }