基于asio的httpclient实现

基于Asio实现一个简易的httpclient

Asio是C++的一个高性能网络编程库,提供了跨平台的网络和底层I/O编程接口,包括tcp,udp等sockets通信,以及异步编程模型。它的设计目标是为C++开发者提供一种简单、直接的方式来处理网络通信和并行I/O操作,同时保持高效和灵活性。

知识点

  • 使用asio::io_context ioctx;作为整个网络IO和回调的上下文
  • 使用std::thread processor;作为ioctx的执行线程,只需要在线程函数里执行ioctx.run()即可触发io事件循环工作
  • 使用asio::executor_work_guard<asio::io_context::executor_type> work;保证ioctx不会因为没有执行任务而结束,导致线程退出
  • 使用 asio::ip::tcp::resolver resolver_;进行dns域名解析
  • 使用std::promise/std::future进行异步任务同步等待,类似于javascript的async/await

源码

https://github.com/samxfb/cpp-httpclient

编译输出cpp-httpclient

Usage:
./cpp-httpclient [ip] [port] [method:GET/POST...] [url/path]
./cpp-httpclient --host [host] [method:GET/POST...] [url/path]

测试用例

1、借助在线的http服务(https://httpbin.org/)

./cpp-httpclient --host httpbin.org GET /get

connect httpbin.org [ip 184.73.216.86, port 80]

RESULT: HTTP/1.1 200  OK
response message:
{
  "args": {}, 
  "headers": {
    "Accept": "*/*", 
    "Host": "httpbin.org", 
    "X-Amzn-Trace-Id": "Root=1-65ab4f91-7370ba8a2d5dee213fb955d6"
  }, 
  "origin": "218.108.104.131", 
  "url": "http://httpbin.org/get"
}

2、自己搭建一个简易的静态http服务器

  • 基于apache搭建

详见(Linux系统下Web文件系统搭建)

  • 使用python自带的http.server模块

python3 -m http.server 9000, 端口号为9000

  • 基于Node.js的轻量级静态HTTP服务器http-server

安装:npm install -g http-server
运行:http-server --port 9000

以下测试启动node.js http-server进行:

(base) sam@SamdeMacBook-Pro:~/Desktop/test/cpp-httpclient$ http-server --port 9000
Starting up http-server, serving ./

http-server version: 14.1.1

http-server settings: 
CORS: disabled
Cache: 3600 seconds
Connection Timeout: 120 seconds
Directory Listings: visible
AutoIndex: visible
Serve GZIP Files: false
Serve Brotli Files: false
Default File Extension: none

Available on:
  http://127.0.0.1:9000
  http://10.18.146.230:9000
Hit CTRL-C to stop the server

http客户端请求

./cpp-httpclient 127.0.0.1 9000 GET /build.sh

RESULT: HTTP/1.1 200  OK
response message:
#!/bin/bash

g++ -std=c++11 -I. -I./thirdparty/asio/asio/include -pthread -o cpp-httpclient test.cpp