C++ Boost::Asio
Asio
Boost.Asio 是一个跨平台的C++库,用于网络和底层I/O编程,它使用现代C++方法为开发人员提供一致的异步模型。
库学习建议
核心概念优先级:
- io_context + 异步操作模型 ✓
- TCP/UDP编程基础 ✓
- 异步回调与completion handler ✓
- 定时器与deadline_timer ✓
- 简单的异步链 ✓
可暂缓的内容:
- 复杂的proactor模式理论
- 所有高级特性(如协程支持)
- 性能优化细节
定时器
通过展示如何对定时器执行阻塞来介绍 asio
所有的 asio 类都可以通过简单的包含 <boost/asio.hpp> 头文件来使用
Timer 1
所有使用 asio 的程序都需要 至少有一个 I/O 执行上下文 ,例如 io_contex 或 thread_pool 对象。I/O 执行上下文提供对 I/O 功能的访问。
1 | void test1() |
我们首先在函数的开头声明一个 io_context 类型的对象。
接下来的 boost::asio::steady_timer 类型的对象。提供 I/O 功能的和兴 asio 类总是接受一个执行器,或者对执行上下文的引用(如 io_context),作为它们的第一个构造函数参数。构造函数的第二个参数将定时器设置为从现在起 2700 毫秒后到期。
以上示例中,对定时器执行 阻塞等待 。即,对 steady_timer::wait() 的调用将不会返回,直到定时器过期。定时器始终处于两种状态之一: 已过期 或 未过期 。如果在已过期的定时器上调用 steady_timer::wait() 函数,他将立即返回。
Timer 2
使用 asio 的异步功能意味着提供一个 完成令牌 。它决定了当 异步操作 完成时,结果将如何传递给 完成处理程序 。
1 | void print(const boost::system::error_code& e) |
调用 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 | void print_v2(const boost::system::error_code& e, boost::asio::steady_timer* t, int* count) |
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 | class printer |
Timer 5
可以使用 strand 类模板在多线程程序中同步完成处理程序。
asio库保证完成处理程序仅会从当前正在调用 boost::asio::io_context::run() 的线程中调用。因此,仅从一个线程调用 boost::asio::io_context::run() 可以确保完成处理程序不会并发运行。
单线程方法通常是开始开发使用 asio 的应用程序的最佳选择。缺点是它对程序,特别是服务器的限制:
- 当处理程序可能需要很长时间才能完成时,响应性差
- 无法在多处理器系统上扩展。
为了突破这些限制,可以使用线程池进行 boost::asio::io_context::run() 的调用。但是,由于允许处理程序并发执行,当处理程序可能访问共享的线程不安全资源时,需要一种同步方法。
1 | class printer |
1 | void test1() |
其中 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() 的调用:
- 两个线程 共享 同一个 boost::asio::io_context 对象
- 两个线程 共同处理所有的异步操作
- boost::strand 的作用是确保 线程安全
TCP/UDP的同步-异步处理
同步TCP客户端
1 |
|
tcp::socket 可以创建一个套接字,使用 boost::asio::connect() 函数自动进行端点列表的连接。
boost::asio::buffer() 函数会自动确定数组的大小,可以防止缓冲区溢出。可以传入 std::array char[] std::vector 。
当服务器关闭连接时, ip::tcp::socket::read_some() 函数将以 boost::asio::error::eof 错误退出。
同步TCP服务端
1 |
|
通过创建一个 ip::tcp::acceptor 对象来监听新的连接。用于 ipv4 在 13 端口进行监听。
异步TCP服务端
1 |
|
UDP客户端
1 |
|
异步TCP-UDP服务端
1 |
|
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
53void 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
20void 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
39void 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
65class 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
87class 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
68void 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();
}