如何處理 EADDRINUSE
錯誤
偵聽時最常見的錯誤之一是 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)
處理此問題的方法之一是捕捉錯誤並在一段時間後重試
- 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.dev.org.tw/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;
// ...
});