Skip to content

WebSocket 连接失败

快速摘要

你的 WebSocket 连接失败到 打开因为服务器是 不运行, URL 是错误, or protocol 是 mismatched.

为什么发生

  • WebSocket 服务器是 不运行 or 不 listening on expected port

  • Using ws:// on HTTPS page (必须 use wss:// for secure 连接)

  • WebSocket URL 是不正确 or 端点做 不 exist

  • proxy or firewall 块 WebSocket 连接

最小示例

✗ 错误代码
// HTTPS page trying to use ws:// (insecure)
const ws = new WebSocket("ws://example.com/ws");
// Error: Mixed content - blocked by browser

// Server not running
const ws = new WebSocket("wss://example.com:8080/ws");
// Error: Connection refused
✓ 修复代码
// Use wss:// on HTTPS pages
const ws = new WebSocket("wss://example.com/ws");
ws.onerror = (err) => console.error("WebSocket error:", err);
ws.onclose = () => console.log("Disconnected - implement reconnect");

On HTTPS pages, use wss:// (secure WebSocket) 不 ws://. 添加错误 handling for onerror and onclose 事件, and implement reconnection logic for production reliability.

如何诊断

  • 检查浏览器 console for WebSocket 错误消息

  • 验证 WebSocket URL 是正确 (ws:// or wss:// + host + port + path)

  • 测试 WebSocket 服务器 independently (e.g., 使用 wscat)

  • 检查如果 page 是 HTTPS — 它需要 wss:// 不 ws://

如何修复

  • 开始 WebSocket 服务器 and 验证它 是 listening

  • Use wss:// on HTTPS pages and ws:// on HTTP pages

  • 正确 WebSocket URL path and port

  • 配置 proxy 到向前 WebSocket 连接

如何预防

  • 总是 use wss:// on production HTTPS sites

  • Implement reconnection logic for dropped 连接

  • 添加错误 handling on WebSocket onerror and onclose 事件

相关资源

相关术语

相关课程

  • HTTP

    HTTP and WebSocket protocols.

← 返回语言