写一个C++异步回调案例
时间: 2024-09-12 11:10:26 浏览: 78
在C++中,我们可以使用各种异步编程模型,例如Boost.Asio、C++17的std::async和std::future等。这里以Boost.Asio库为例,展示一个简单的异步网络读取回调案例:
```cpp
#include <iostream>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
void on_read(const boost::system::error_code& error, size_t bytes_transferred,
std::string data) {
if (!error) {
std::cout << "Received " << bytes_transferred << " bytes of data: " << data.substr(0, bytes_transferred) << '\n';
} else {
std::cerr << "Error reading from the socket: " << error.message() << '\n';
}
}
int main() {
try {
boost::asio::io_context io_context;
tcp::resolver resolver(io_context);
tcp::resolver::results_type endpoints = resolver.resolve("www.example.com", "http");
tcp::socket socket(io_context);
for (auto const& endpoint : endpoints) {
boost::asio::connect(socket, endpoint);
break; // Assume only one endpoint will be used.
}
boost::asio::streambuf receive_buffer;
boost::asio::read(socket, receive_buffer, boost::asio::transfer_all());
auto read_result = boost::asio::buffer_cast<const char*>(receive_buffer.data());
size_t length = receive_buffer.size();
std::string received_data(read_result, read_result + length);
std::string request = "GET / HTTP/1.1\r\nHost: www.example.com\r\nConnection: close\r\n\r\n";
boost::asio::write(socket, boost::asio::buffer(request));
socket.async_read_some(boost::asio::dynamic_buffer(receive_buffer),
on_read); // 异步读取数据
io_context.run(); // 主循环,等待所有操作完成
}
catch (const std::exception& e) {
std::cerr << "Exception caught: " << e.what() << '\n';
}
return 0;
}
```
这个程序首先解析域名到IP地址,连接到服务器,然后发送一个HTTP GET请求。当接收到响应的一部分时,它会调用`on_read`回调函数,将接收到的数据传递给它。`main`函数通过`io_context.run()`保持运行,直到所有的I/O操作都完成。
阅读全文