C++ WebSocket客户端的“Connection refused”Boost.beast库

ojsjcaue  于 2023-05-17  发布在  其他
关注(0)|答案(1)|浏览(142)

我有这样的Python代码:

Server.py

import asyncio
import websockets
import random

async def random_number(websocket, path):
    while True:
        number = random.randint(1, 100)
        await websocket.send(str(number))
        await asyncio.sleep(1)

start_server = websockets.serve(random_number, "localhost", 8765)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

它通过localhost发送随机数:8765。我测试了一下,它可以使用不同的Python脚本:

Client.py

import asyncio
import websockets

async def websocket_client():
    uri = "ws://localhost:8765"
    async with websockets.connect(uri) as websocket:
        while True:
            message = await websocket.recv()
            print(f"Received: {message}")

asyncio.get_event_loop().run_until_complete(websocket_client())

现在,我想进一步涉及C++。基本上,我希望能够在C++中做Client.py正在做的事情。因此,我写道:

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

namespace beast = boost::beast;
namespace http = beast::http;
namespace websocket = beast::websocket;
namespace net = boost::asio;
using tcp = boost::asio::ip::tcp;

int main(int argc, char* argv[]) {
    try {
        const std::string host = "localhost";
        const std::string port = "8765";
        const std::string target = "/";

        net::io_context ioc;
        tcp::resolver resolver{ioc};
        websocket::stream<tcp::socket> ws{ioc};

        auto const results = resolver.resolve(host, port);
        net::connect(ws.next_layer(), results.begin(), results.end());

        ws.handshake(host + ':' + port, target);

        for (;;) {
            beast::flat_buffer buffer;
            ws.read(buffer);
            std::string message = beast::buffers_to_string(buffer.data());
            std::cout << "Received: " << message << std::endl;
        }
    }
    catch (std::exception const& e) {
        std::cerr << "Error: " << e.what() << std::endl;
        return EXIT_FAILURE;
    }
}

我得到:错误:connect:连接被拒绝这是怎么回事?

aor9mmx1

aor9mmx11#

对我来说效果很好,所以这表明你的环境有些不同。
也许localhost实际上没有解析为127.0.0.1,或者防火墙干扰了。你可以通过直接连接来避开第一个。变化

auto const results = resolver.resolve(host, port);
    net::connect(ws.next_layer(), results.begin(), results.end());

ws.next_layer().connect({{}, 8765});

否则,我建议使用wireshark/ethereal/tcpdump等查看网络数据包。找出任何可能相关的差异
使用提供的代码在本地为我现场演示:

相关问题