You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否用C++ Boost Beast/Asio连接Node.js Socket.IO服务器?握手失败求助

问题:Boost Beast WebSocket客户端与Socket.IO服务器握手失败

我正尝试搭建一个基础应用,用C的Boost Beast/Asio WebSocket客户端连接本地Node.js(Express+Socket.IO)服务器,服务器监听localhost:3000。C程序通过命令行参数websocket-client-sync 127.0.0.1 3000 "connection"发送消息,但握手阶段失败,报错:

Error: end of stream [beast.http:1 at C:\libraries\boost\beast\http\impl\read.hpp:366:13 in function 'read_some']

相关代码

Main.cpp

#include <boost/beast.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/beast/http.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <cstdlib>
#include <iostream>
#include <string>

namespace beast = boost::beast;         // from <boost/beast.hpp>
namespace http = beast::http;           // from <boost/beast/http.hpp>
namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp>
namespace net = boost::asio;            // from <boost/asio.hpp>
using tcp = boost::asio::ip::tcp;       // from <boost/asio/ip/tcp.hpp>

// Sends a WebSocket message and prints the response
int main(int argc, char** argv)
{
    std::cout << "beginning\n";
    try
    {
        std::cout << "Argument Count: " << argc << " \n";
        std::cout << "Path: " << argv[0] << "\n";
        std::cout << "Command: " << argv[1] << "\n";
        std::cout << "Host: " << argv[2] << "\n";
        std::cout << "Port: " << argv[3] << "\n";
        std::cout << "Message: " << argv[4] << "\n";

        // Check command line arguments.
        if (argc != 5)
        {   
            // This displays if there is an error
            std::cerr <<
                "Usage: websocket-client-sync <host> <port> <text>\n" <<
                "Example:\n" <<
                "    websocket-client-sync echo.websocket.org 80 \"Hello, world!\"\n";
            return EXIT_FAILURE;
        }
        std::string host = argv[2];
        auto const  port = argv[3];
        auto const  text = argv[4];

        // The io_context is required for all I/O
        net::io_context ioc;
        std::cout << "IO Context Obtained\n";

        // These objects perform our I/O
        tcp::resolver resolver{ ioc };
        websocket::stream<tcp::socket> ws{ ioc };
        std::cout << "IO Performed\n";

        // Look up the domain name
        auto const results = resolver.resolve(host, port);
        std::cout << "Domain name looked up\n";

        // Make the connection on the IP address we get from a lookup
        auto ep = net::connect(ws.next_layer(), results);
        std::cout << "Connection made from IP address\n";

        // Update the host_ string. This will provide the value of the
        // Host HTTP header during the WebSocket handshake.
        // See https://tools.ietf.org/html/rfc7230#section-5.4
        host += ':' + std::to_string(ep.port());
        std::cout << "Host string updated\n";

        // Set a decorator to change the User-Agent of the handshake
        ws.set_option(websocket::stream_base::decorator(
            [](websocket::request_type& req)
            {
                req.set(http::field::user_agent,
                    std::string(BOOST_BEAST_VERSION_STRING) +
                    " websocket-client-coro");
            }));
        std::cout << "User-Agent Changed\n";

        // Perform the websocket handshake
        ws.handshake(host, "/");
        std::cout << "Handshake Performed\n";

        // Send the message
        ws.write(net::buffer(std::string(text)));
        std::cout << "Message Sent\n";

        // This buffer will hold the incoming message
        beast::flat_buffer buffer;
        std::cout << "Incoming Message held by buffer\n";

        // Read a message into our buffer
        ws.read(buffer);
        std::cout << "Message read into buffer \n";

        // Close the WebSocket connection
        ws.close(websocket::close_code::normal);
        std::cout << "Connection Closed Gracefully\n";

        // If we get here then the connection is closed gracefully

        // The make_printable() function helps print a ConstBufferSequence
        std::cout << beast::make_printable(buffer.data()) << std::endl;
        std::cout << "ConstBufferSequence Printed\n";
    }
    catch (std::exception const& e)
    {
        std::cerr << "Error: " << e.what() << std::endl;
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

index.js

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);


app.get('/', (req, res) => {

  res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
  console.log('a user connected');
  socket.on('disconnect', () => {
    console.log('user disconnected');
  });
  socket.on('chat message', (msg) => {
    io.emit('chat message', msg);
    console.log('chat message');
  });
});




server.listen(3000, () => {
  console.log('listening on *:3000');
});
问题原因与修复方案

核心原因

Socket.IO不是标准WebSocket协议,它在标准WebSocket基础上封装了自定义协议层,包含专属握手流程、命名空间、房间管理等额外逻辑。Boost Beast是标准WebSocket客户端,直接连接Socket.IO服务器会因协议不兼容导致握手失败。

修复方案

有两种可行解决思路:

思路1:Node.js端改用标准WebSocket服务器

如果不需要Socket.IO的额外功能,可换成Node.js原生ws库实现标准WebSocket服务器:

修改后的index.js:

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const WebSocket = require('ws');

const wss = new WebSocket.Server({ server });

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

wss.on('connection', (ws) => {
  console.log('a user connected');
  ws.on('message', (data) => {
    console.log(`received: ${data}`);
    // 回显消息给客户端
    ws.send(data);
  });
  ws.on('close', () => {
    console.log('user disconnected');
  });
});

server.listen(3000, () => {
  console.log('listening on *:3000');
});

思路2:C++端使用Socket.IO客户端库

如果必须保留Socket.IO的功能,C++需使用支持Socket.IO协议的客户端库,比如官方维护的socket.io-client-cpp。示例代码如下:

#include <socketio_client.hpp>

int main() {
    sio::client client;
    client.connect("http://127.0.0.1:3000");
    
    client.socket()->on("chat message", [&](const sio::message::ptr& data) {
        std::cout << "Received message: " << data->get_string() << std::endl;
    });
    
    // 发送消息
    client.socket()->emit("chat message", "connection");
    
    // 保持程序运行
    std::string input;
    std::getline(std::cin, input);
    client.disconnect();
    return 0;
}

额外注意点

原C++代码存在命令行参数解析错误:

  • 代码判断argc !=5,但实际命令行websocket-client-sync 127.0.0.1 3000 "connection"的argc为4(程序名+3个参数),会触发参数校验失败。需修改为:
if (argc != 4) {
    std::cerr << "Usage: websocket-client-sync <host> <port> <text>\n";
    return EXIT_FAILURE;
}
std::string host = argv[1];
auto const port = argv[2];
auto const text = argv[3];

内容的提问来源于stack exchange,提问作者Captain Dando

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 03:47:22