使用@microsoft/signalr连接WebSocket失败求助
SignalR WebSocket连接失败排查与解决
错误信息
Error: WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled. at webSocket.onclose (C:\Webstorm Projects\AccountCreator\node_modules\@microsoft\signalr\dist\cjs\WebSocketTransport.js:110:28) at WebSocket.onClose (C:\Webstorm Projects\AccountCreator\node_modules\ws\lib\event-target.js:136:16) at WebSocket.emit (node:events:519:28) at WebSocket.emitClose (C:\Webstorm Projects\AccountCreator\node_modules\ws\lib\websocket.js:236:12) at Object.onceWrapper (node:events:633:28) at ClientRequest.emit (node:events:519:28) at emitAbortNT (node:_http_client:430:7) at process.processTicksAndRejections (node:internal/process/task_queues:81:21)
当前代码
const signalR = require('@microsoft/signalr'); const connection = new signalR.HubConnectionBuilder() .withUrl('https://realtime-signalr.roblox.com/userhub', { transport: signalR.HttpTransportType.WebSockets, skipNegotiation: true }) .build().start();
排查方向与解决方法
1. 移除强制跳过协商配置
Roblox的SignalR Hub需要通过协商步骤获取连接ID等核心信息,直接设置skipNegotiation: true会导致服务器无法识别连接请求,需删除该配置:
const connection = new signalR.HubConnectionBuilder() .withUrl('https://realtime-signalr.roblox.com/userhub') .build();
2. 取消强制WebSocket传输
强制指定transport: WebSockets会跳过SignalR的自动降级逻辑,若服务器不支持直接WebSocket握手,会直接触发连接失败。建议让客户端自动选择最优传输方式:
// 移除transport配置,由SignalR自动协商传输方式 const connection = new signalR.HubConnectionBuilder() .withUrl('https://realtime-signalr.roblox.com/userhub') .build();
3. 补充认证信息
Roblox的userhub属于用户关联服务,需要携带合法的会话凭证(如.ROBLOSECURITY Cookie)才能建立连接,未认证会被服务器拒绝:
const connection = new signalR.HubConnectionBuilder() .withUrl('https://realtime-signalr.roblox.com/userhub', { headers: { 'Cookie': '.ROBLOSECURITY=你的Roblox会话Cookie' } }) .build();
4. 检查网络与代理限制
- 关闭本地代理、防火墙,测试连接是否恢复
- 验证
wss://realtime-signalr.roblox.com的443端口是否可访问(可通过telnet realtime-signalr.roblox.com 443测试)
额外排查步骤
发送GET请求到https://realtime-signalr.roblox.com/userhub/negotiate,根据响应判断问题:
- 返回401/403:需补充认证信息
- 返回404:确认端点地址是否正确
- 返回含
connectionId的JSON:端点正常,问题出在客户端配置
内容的提问来源于stack exchange,提问作者Alfie
相关产品推荐
相关产品推荐

