使用Boost.Beast的C++ WebSocket客户端遇Connection refused问题
WebSocket客户端连接拒绝问题排查
我编写了如下Python WebSocket服务端代码(Server.py),通过localhost:8765发送随机数,且已用另一个Python客户端脚本(Client.py)验证该服务端可正常工作:
# 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()
# 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实现与Client.py完全相同的功能,于是编写了基于Boost.Beast库的C WebSocket客户端代码:
#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; } }
但运行该C++客户端时出现错误:Error: connect: Connection refused,请问这是什么原因?
内容的提问来源于stack exchange,提问作者IceCode
相关产品推荐
相关产品推荐

