我有这样的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:连接被拒绝这是怎么回事?
1条答案
按热度按时间aor9mmx11#
对我来说效果很好,所以这表明你的环境有些不同。
也许
localhost
实际上没有解析为127.0.0.1
,或者防火墙干扰了。你可以通过直接连接来避开第一个。变化到
否则,我建议使用wireshark/ethereal/tcpdump等查看网络数据包。找出任何可能相关的差异
使用提供的代码在本地为我现场演示: