STTNet 0.7.0

Demo:HTTP 客户端

可构建、可运行、可验证,并与仓库 examples 目录中的源码保持一致。

1. 示例内容

完整源码中的关键调用均有中文注释,页面同时给出运行命令、验证方法和可调整参数。

2. 构建与运行

cmake --build build --target sttnet_http_client --parallel
./build/examples/sttnet_http_client

3. 运行结果

先启动监听 127.0.0.1:8080 的 HTTP 服务,再运行客户端。
预期:输出一份完整 HTTP 响应。

4. 完整源码

#include <sttnet.h>

#include <iostream>

int main()
{
    using stt::network::HttpClient;

    // HttpClient 是同步客户端;生产环境为连接和读取设置有限超时,
    // 调用发生在 WorkerPool 等非 Reactor 上下文中。
    HttpClient client;

    if(!client.getRequest("http://127.0.0.1:8080/ping", "",
                          "Connection: close", 5))
    {
        std::cerr << "request could not be sent\n";
        return 1;
    }

    // 发送成功不等于已经收到完整响应。
    if(!client.isReturn())
    {
        std::cerr << "server did not return a complete HTTP response\n";
        return 2;
    }

    std::cout << "--- response headers ---\n" << client.header
              << "\n--- response body ---\n" << client.body << '\n';
    return 0;
}