STTNet 0.7.0

Demo:协议字符串解析

展示 URL/Query 提取、大小写无关的 Header 查找和 WebSocket Accept 计算。

1. 示例内容

示例中的关键调用使用中文注释,并与仓库源码、CMake 目标和当前 API 保持一致。

2. 构建与运行

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

3. 运行结果

./build/examples/sttnet_protocol_parsing
预期:输出 id=42 和 application/json,WebSocket Accept 为 s3pPLMBiTxaQ9kYGzzhZRbK+xOo=;userid=7 不会被误识别为 id。

4. 完整源码

#include <sttnet.h>

#include <iostream>
#include <string>

int main()
{
    using stt::data::HttpStringUtil;
    using stt::data::WebsocketStringUtil;

    const std::string url="http://127.0.0.1:8080/users?userid=7&id=42&page=2";
    std::string ip;
    int port=0;
    std::string locationAndQuery;
    std::string path;
    std::string query;
    std::string id;

    // 这些是轻量提取工具,不会对百分号转义执行 URL decode,也不是用于
    // 处理恶意输入的完整 URI 标准解析器。
    HttpStringUtil::getIP(url,ip);
    HttpStringUtil::getPort(url,port);
    HttpStringUtil::getLocPara(url,locationAndQuery);
    HttpStringUtil::get_location_str(locationAndQuery,path);
    HttpStringUtil::getPara(locationAndQuery,query);

    // Query 键按字段边界匹配:id 不会误匹配 userid。
    HttpStringUtil::get_value_str(locationAndQuery,id,"id");
    std::cout << "ip=" << ip << '\n'
              << "port=" << port << '\n'
              << "location=" << locationAndQuery << '\n'
              << "path=" << path << '\n'
              << "query=" << query << '\n'
              << "id=" << id << '\n';

    const std::string rawHeaders=
        "content-type:\tapplication/json\r\n"
        "Connection: keep-alive\r\n";
    std::string contentType;

    // HTTP 字段名不区分大小写;工具会跳过冒号后的可选空格和 Tab。
    // 服务端 Handler 通常直接使用 headerValue()。
    HttpStringUtil::get_value_header(rawHeaders,contentType,"Content-Type");
    std::cout << "content-type=" << contentType << '\n';

    // 这里计算 RFC 6455 的 Sec-WebSocket-Accept。业务代码通常应让
    // WebSocketServer 自动完成握手。
    std::string websocketKey="dGhlIHNhbXBsZSBub25jZQ==";
    WebsocketStringUtil::transfer_websocket_key(websocketKey);
    std::cout << "websocket_accept=" << websocketKey << '\n';
    return 0;
}