EADDRINUSE エラーの処理方法
リスニング時に発生する最も一般的なエラーの 1 つは EADDRINUSE です。これは別のサーバーが要求された port/path/handle で既にリスニングしている場合に発生します。
node:events:489
      throw er; // Unhandled 'error' event
      ^
Error: listen EADDRINUSE: address already in use :::8080
    at Server.setupListenHandle [as _listen2] (node:net:1829:16)
    at listenInCluster (node:net:1877:12)
    at Server.listen (node:net:1965:7)
このエラーを処理する 1 つの方法は、エラーをキャッチして一定時間後に再試行することです。
- CommonJS
- ES モジュール
- TypeScript
const { createServer } = require("node:http");
const { Server } = require("socket.io");
const httpServer = createServer();
const io = new Server(httpServer);
const PORT = process.env.PORT || 8080;
io.on("connection", (socket) => {
  // ...
});
httpServer.on("error", (e) => {
  if (e.code === "EADDRINUSE") {
    console.error("Address already in use, retrying in a few seconds...");
    setTimeout(() => {
      httpServer.listen(PORT);
    }, 1000);
  }
});
httpServer.listen(PORT);
import { createServer } from "node:http";
import { Server } from "socket.io";
const httpServer = createServer();
const io = new Server(httpServer);
const PORT = process.env.PORT || 8080;
io.on("connection", (socket) => {
  // ...
});
httpServer.on("error", (e) => {
  if (e.code === "EADDRINUSE") {
    console.error("Address already in use, retrying in a few seconds...");
    setTimeout(() => {
      httpServer.listen(PORT);
    }, 1000);
  }
});
httpServer.listen(PORT);
import { createServer } from "node:http";
import { Server } from "socket.io";
const httpServer = createServer();
const io = new Server(httpServer);
const PORT = process.env.PORT || 8080;
io.on("connection", (socket) => {
  // ...
});
httpServer.on("error", (e) => {
  if (e.code === "EADDRINUSE") {
    console.error("Address already in use, retrying in a few seconds...");
    setTimeout(() => {
      httpServer.listen(PORT);
    }, 1000);
  }
});
httpServer.listen(PORT);
参照: https://node.dokyumento.jp/api/net.html#serverlisten
ヒント
テスト時には、特定のポートを使用する必要がない場合があります。ポートを省略するだけで、オペレーティングシステムが自動的に任意の未使用ポートを拾います。
- CommonJS
- ES モジュール
- TypeScript
const { createServer } = require("node:http");
const { Server } = require("socket.io");
const httpServer = createServer();
const io = new Server(httpServer);
httpServer.listen(() => {
  const port = httpServer.address().port;
  // ...
});
import { createServer } from "node:http";
import { Server } from "socket.io";
const httpServer = createServer();
const io = new Server(httpServer);
httpServer.listen(() => {
  const port = httpServer.address().port;
  // ...
});
import { createServer } from "node:http";
import { type AddressInfo } from "node:net";
import { Server } from "socket.io";
const httpServer = createServer();
const io = new Server(httpServer);
httpServer.listen(() => {
  const port = (httpServer.address() as AddressInfo).port;
  // ...
});