STTNet 0.7.0

Demo:WebSocket 客户端

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

1. 示例内容

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

2. 构建与运行

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

3. 运行结果

先启动 sttnet_websocket_echo,再运行本客户端。
预期:客户端收到服务端回显的消息。

4. 完整源码

#include <sttnet.h>

#include <chrono>
#include <iostream>
#include <thread>

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

    WebSocketClient client;

    // 回调运行在客户端内部监听线程。
    client.setFunction(
        [](const std::string &message, WebSocketClient &) {
            std::cout << "received: " << message << '\n';
            return true; // 返回 false 会关闭 WebSocket 连接。
        });

    if(!client.connect("ws://127.0.0.1:5050/echo"))
    {
        std::cerr << "WebSocket connection failed\n";
        return 1;
    }

    if(!client.sendMessage("hello from STTNet client"))
    {
        std::cerr << "send failed\n";
        client.close(1011, "send failed");
        return 2;
    }

    // 给异步接收回调留出打印回显的时间。
    std::this_thread::sleep_for(std::chrono::seconds(1));
    client.close(1000, "demo complete");
    return 0;
}