MeWrite Docs

WebSocket: Close code 1006 (Abnormal Closure)

WebSocket異常終了エラーの解決方法

概要

WebSocket接続が正常なクローズハンドシェイクなしに終了した場合に発生するエラーです。

エラーメッセージ

WebSocket connection to 'wss://...' failed: Connection closed before receiving a handshake response

クローズコード: 1006

原因

  1. ネットワーク切断: 接続が突然失われた
  2. サーバークラッシュ: サーバー側でエラー発生
  3. プロキシタイムアウト: ロードバランサーのアイドルタイムアウト
  4. TLSエラー: SSL/TLS設定の問題

解決策

1. 再接続ロジック

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class ReconnectingWebSocket {
  constructor(url) {
    this.url = url;
    this.reconnectDelay = 1000;
    this.connect();
  }

  connect() {
    this.ws = new WebSocket(this.url);

    this.ws.onclose = (event) => {
      if (event.code === 1006) {
        setTimeout(() => {
          this.reconnectDelay = Math.min(this.reconnectDelay * 2, 30000);
          this.connect();
        }, this.reconnectDelay);
      }
    };

    this.ws.onopen = () => {
      this.reconnectDelay = 1000;
    };
  }
}

2. Ping/Pongでキープアライブ

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// クライアント
setInterval(() => {
  if (ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify({ type: 'ping' }));
  }
}, 30000);

// サーバー (ws)
wss.on('connection', (ws) => {
  ws.isAlive = true;
  ws.on('pong', () => { ws.isAlive = true; });
});

setInterval(() => {
  wss.clients.forEach((ws) => {
    if (!ws.isAlive) return ws.terminate();
    ws.isAlive = false;
    ws.ping();
  });
}, 30000);

3. ALB/Nginxタイムアウト延長

1
2
3
# Nginx
proxy_read_timeout 86400s;
proxy_send_timeout 86400s;

よくある間違い

  • ハートビートなしでアイドル接続
  • 再接続時の指数バックオフなし

WebSocket の他のエラー

最終更新: 2025-12-09