使用asio进行异步下载http
下面是官方demo, 给人耳目一新的感觉,以前是总是把c++当成有类功能的C,看完这个感觉不用自己造轮子了,还是要跟上时代的步伐
//
// async_client.cpp
// ~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// #include <iostream>
#include <istream>
#include <ostream>
#include <string>
#include <boost/asio.hpp>
#include <boost/bind.hpp> using boost::asio::ip::tcp; class client
{
public:
client(boost::asio::io_context& io_context,
const std::string& server, const std::string& path)
: resolver_(io_context),
socket_(io_context)
{
// Form the request. We specify the "Connection: close" header so that the
// server will close the socket after transmitting the response. This will
// allow us to treat all data up until the EOF as the content.
std::ostream request_stream(&request_);
request_stream << "GET " << path << " HTTP/1.0\r\n";
request_stream << "Host: " << server << "\r\n";
request_stream << "Accept: */*\r\n";
request_stream << "Connection: close\r\n\r\n"; // Start an asynchronous resolve to translate the server and service names
// into a list of endpoints.
resolver_.async_resolve(server, "http",
boost::bind(&client::handle_resolve, this,
boost::asio::placeholders::error,
boost::asio::placeholders::results));
} private:
void handle_resolve(const boost::system::error_code& err,
const tcp::resolver::results_type& endpoints)
{
if (!err)
{
// Attempt a connection to each endpoint in the list until we
// successfully establish a connection.
boost::asio::async_connect(socket_, endpoints,
boost::bind(&client::handle_connect, this,
boost::asio::placeholders::error));
}
else
{
std::cout << "Error: " << err.message() << "\n";
}
} void handle_connect(const boost::system::error_code& err)
{
if (!err)
{
// The connection was successful. Send the request.
boost::asio::async_write(socket_, request_,
boost::bind(&client::handle_write_request, this,
boost::asio::placeholders::error));
}
else
{
std::cout << "Error: " << err.message() << "\n";
}
} void handle_write_request(const boost::system::error_code& err)
{
if (!err)
{
// Read the response status line. The response_ streambuf will
// automatically grow to accommodate the entire line. The growth may be
// limited by passing a maximum size to the streambuf constructor.
boost::asio::async_read_until(socket_, response_, "\r\n",
boost::bind(&client::handle_read_status_line, this,
boost::asio::placeholders::error));
}
else
{
std::cout << "Error: " << err.message() << "\n";
}
} void handle_read_status_line(const boost::system::error_code& err)
{
if (!err)
{
// Check that response is OK.
std::istream response_stream(&response_);
std::string http_version;
response_stream >> http_version;
unsigned int status_code;
response_stream >> status_code;
std::string status_message;
std::getline(response_stream, status_message);
if (!response_stream || http_version.substr(, ) != "HTTP/")
{
std::cout << "Invalid response\n";
return;
}
if (status_code != )
{
std::cout << "Response returned with status code ";
std::cout << status_code << "\n";
return;
} // Read the response headers, which are terminated by a blank line.
boost::asio::async_read_until(socket_, response_, "\r\n\r\n",
boost::bind(&client::handle_read_headers, this,
boost::asio::placeholders::error));
}
else
{
std::cout << "Error: " << err << "\n";
}
} void handle_read_headers(const boost::system::error_code& err)
{
if (!err)
{
// Process the response headers.
std::istream response_stream(&response_);
std::string header;
while (std::getline(response_stream, header) && header != "\r")
std::cout << header << "\n";
std::cout << "\n"; // Write whatever content we already have to output.
if (response_.size() > )
std::cout << &response_; // Start reading remaining data until EOF.
boost::asio::async_read(socket_, response_,
boost::asio::transfer_at_least(),
boost::bind(&client::handle_read_content, this,
boost::asio::placeholders::error));
}
else
{
std::cout << "Error: " << err << "\n";
}
} void handle_read_content(const boost::system::error_code& err)
{
if (!err)
{
// Write all of the data that has been read so far.
std::cout << &response_; // Continue reading remaining data until EOF.
boost::asio::async_read(socket_, response_,
boost::asio::transfer_at_least(),
boost::bind(&client::handle_read_content, this,
boost::asio::placeholders::error));
}
else if (err != boost::asio::error::eof)
{
std::cout << "Error: " << err << "\n";
}
} tcp::resolver resolver_;
tcp::socket socket_;
boost::asio::streambuf request_;
boost::asio::streambuf response_;
}; int main(int argc, char* argv[])
{
try
{
if (argc != )
{
std::cout << "Usage: async_client <server> <path>\n";
std::cout << "Example:\n";
std::cout << " async_client www.boost.org /LICENSE_1_0.txt\n";
return ;
} boost::asio::io_context io_context;
client c(io_context, argv[], argv[]);
io_context.run();
}
catch (std::exception& e)
{
std::cout << "Exception: " << e.what() << "\n";
} return ;
}
直接拿来使用也是没有问题的,太爽了
使用asio进行异步下载http的更多相关文章
- Android多线程分析之五:使用AsyncTask异步下载图像
Android多线程分析之五:使用AsyncTask异步下载图像 罗朝辉 (http://www.cnblogs.com/kesalin) CC 许可,转载请注明出处 在本系列文章的第一篇<An ...
- Android多线程分析之一:使用Thread异步下载图像
Android多线程分析之一:使用Thread异步下载图像 罗朝辉 (http://www.cnblogs.com/kesalin) CC 许可,转载请注明出处 打算整理一下对 Android F ...
- WebClient.DownloadFile(线程机制,异步下载文件)
线程机制(避免卡屏),异步下载文件. 我做网站的监控,WebClient.DownloadFile这个方法是我经常用到的,必要的时候肯定是要从网上下载些什么(WebRequest 也可以下载网络文件, ...
- iOS异步下载下载进度条显示
说到http异步下载,首先要知道其中的关键类. 关键类是NSURLConnection NSURLRequest NSMutableURLRequest 委托是 NSURLConnectionDo ...
- unity下载文件三(http异步下载)
异步下载,顾名思义就是不影响你主线程使用客户端的时候,人家在后台搞你的明堂. 直接入主题,既然要下载,首先得请求,请求成功之后进行回调,这就是一个异步过程,异步回调的时间不可控. 1.首先请求下载. ...
- Android 中的异步下载
网上提到最多的就是利用AsyncTask进行异步下载,用android-async-http第三方库的也比较多.这里写点注意事项. 先说说android-async-http,这个库发送请求利用thr ...
- FtpWebRequest FTP异步下载、异步上传文件
异步下载: public interface IPrimaryKey<T> { T GetKey(); } public class DownloadInfo : IPrimaryKey& ...
- Android异步下载图片并且缓存图片到本地
Android异步下载图片并且缓存图片到本地 在Android开发中我们经常有这样的需求,从服务器上下载xml或者JSON类型的数据,其中包括一些图片资源,本demo模拟了这个需求,从网络上加载XML ...
- android AsyncTask异步下载并更新进度条
AsyncTask异步下载并更新进度条 //如果不是很明白请看上篇文章的异步下载 AsyncTask<String, Integer, String> 第一个参数:String 传入 ...
随机推荐
- 将数据导出到 excel ,然后下载下来
private static final String SHEET_NAME = "培养计划表"; /** * @param response * @param trainingN ...
- jquery中的obj.attr()和obj.data
实例一 obj.attr('data-max-width','aa'): obj.data('max-width') 问题 data只会获取第一次select赋值的值 区别 .data每次是从jque ...
- Express multer 文件上传
npm multer 文件上传 Express app 范本就不写了,仅记录一下上传部分的代码. const fs = require('fs'); const express = require(' ...
- C# 递归式快速排序算法
static void Main(string[] args) { Console.WriteLine("************快速排序*****************"); ...
- 关于IDEA顶部栏隐藏问题,
那天手残,点到了 IDEA顶部菜单栏 > View > Appearance >Main Menu ,然后取消了勾选 然后就成了这个样子,没了顶部栏,恢复不过来,不知道如何进行设置 ...
- ubuntu搭建gerrit+gitweb代码审核系统
一.Gerrit的简介 Gerrit是Google开源的一套基于web的代码review工具,它是基于git的版本管理系统.Google开源Gerrit旨在提供一个轻量级框架,用于在代码入库之前对每个 ...
- PAT Basic 1004 成绩排名 (20 分)
读入 n(>)名学生的姓名.学号.成绩,分别输出成绩最高和成绩最低学生的姓名和学号. 输入格式: 每个测试输入包含 1 个测试用例,格式为 第 1 行:正整数 n 第 2 行:第 1 个学生的姓 ...
- Cuda9.0安装
CUDA 9.0安装笔记 最近实验室新购买两块K80的GPU.作为好奇的小猪,当然会自报奋勇去配置环境.在这篇博客中将会介绍在centos7下配置CUDA 9.0的步骤. 1. 什么是CUDA? 引用 ...
- 【LeetCode】451-根据字符出现频率排序
题目描述 给定一个字符串,请将字符串里的字符按照出现的频率降序排列. 示例 1: 输入: "tree" 输出: "eert" 解释: 'e'出现两次,'r'和' ...
- Django学习系列10:保存用户输入——编写表单,发送POST请求
要获取用户输入的待办事项,发送给服务器,这样才能使用某种方式保存待办事项,然后在显示给用户查看. 上次运行测试指出无法保存用户的输入.现在,要使用HTML post请求. 若想让浏览器发送POST请求 ...