0%

Boost asio Reactor 模式编程

今天才发现原来boost.asio也具有Reactor的模式,原文具体如下:

Sometimes a program must be integrated with a third-party library that wants to perform the I/O operations itself. To facilitate this, Boost.Asio includes a null_buffers type that can be used with both read and write operations. A null_buffers operation doesn’t return until the I/O object is “ready” to perform the operation.

As an example, to perform a non-blocking read something like the following may be used:

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

ip::tcp::socket socket(my_io_service);

...

socket.non_blocking(true);

...

socket.async_read_some(null_buffers(), read_handler);

...

void read_handler(boost::system::error_code ec)

{

if (!ec)

{

std::vector<char> buf(socket.available());

socket.read_some(buffer(buf));

}

}

These operations are supported for sockets on all platforms, and for the POSIX stream-oriented descriptor classes.