DEBUG.WIKI
ZgoCloud:多地区部署,按需选节点;日本、美国、香港、德国
V.PS:让项目靠近用户,亚太、欧洲、北美 KVM VPS
晚安云;香港 CN2 ¥15/月

解决 WebSocket 报错 Error 1006 abnormal closure 反向代理超时断连修复

排查 WebSocket 长连接在闲置约 60 秒后抛出 CloseEvent code: 1006 abnormal closure 异常,优化 Nginx proxy_read_timeout 与心跳保活。

问题现象

前端 WebSocket 客户端在建立连接并正常通信后,一旦没有高频数据交互,连接在恰好 60 秒左右突然异常关闭:

WebSocket connection to 'wss://example.com/ws' failed: 
WebSocket is closed before the connection is established.
CloseEvent {isTrusted: true, wasClean: false, code: 1006, reason: ""}

状态码为代表非正常关闭的 1006,未收到服务端的主动关闭帧。

触发根因

根据 RFC 6455 规范,code: 1006 是浏览器客户端保留的状态码,表示底层 TCP 连接在没有收到标准的 WebSocket 关闭帧(Close Frame)的情况下突发中断:

  1. 反向代理(Nginx / Caddy / Cloudflare)空闲超时掐断:Nginx 的 proxy_read_timeout 默认为 60 秒。若在这 60 秒内双向均没有有效数据流动,Nginx 单方面发送 TCP FIN 断开连接;
  2. 中间网络防火墙 NAT 映射超时失效;
  3. 应用层缺乏心跳(Heartbeat / Ping-Pong)机制。

解决步骤

1. 在 Nginx 反向代理中为 WebSocket 单独放宽读取超时

针对 WebSocket 所在的 location,调大读取超时并规范协议升级头:

location /ws {
    proxy_pass http://backend_ws_upstream;
    
    # 启用 HTTP/1.1 协议升级支持
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    
    # 将长连接读取超时由默认 60s 提升至 12 小时(或 1 小时)
    proxy_read_timeout 43200s;
    proxy_send_timeout 43200s;
    
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
}

2. 在应用层实现双向 Ping/Pong 心跳探针(关键生产防护)

无论代理超时设得多么大,中间运营商或云防火墙通常在 60~120 秒无数据后强制剔除 NAT 映射。客户端与服务端必须维持心跳:

客户端心跳实现:

const ws = new WebSocket('wss://example.com/ws');

let heartbeatTimer;
function startHeartbeat() {
  heartbeatTimer = setInterval(() => {
    if (ws.readyState === WebSocket.OPEN) {
      ws.send(JSON.stringify({ type: 'PING' }));
    }
  }, 25000); // 每 25 秒发送一次心跳
}

ws.onopen = () => startHeartbeat();
ws.onclose = () => clearInterval(heartbeatTimer);

3. 客户端实现自动断线重连(Exponential Backoff)

网络抖动在移动端不可避免,结合指数退避算法自动恢复连接。

验证确认

在前后端联调测试中保持长连接空闲 10 分钟:

  • 心跳包每 25 秒平稳流动;
  • 连接持续处于 OPEN 状态,未再发生任何 1006 异常断连。