如何处理 EADDRINUSE
错误
¥How to handle EADDRINUSE
errors
启动 HTTP 服务器时最常见的错误之一是 EADDRINUSE
。当另一台服务器已经在监听所请求的 port
/path
/handle
时,就会发生这种情况:
¥One of the most common errors raised when starting a HTTP server is EADDRINUSE
. This happens when another server is already listening on the requested 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)
在 Linux 上,你可以使用 netstat
命令来识别当前哪个进程使用该端口:
¥On Linux, you can use the netstat
command to identify which process currently uses the port:
$ netstat -ap | grep 8080 | grep LISTEN
tcp 0 0 localhost:8080 0.0.0.0:* LISTEN 12345/node
tip
测试时,你可能不需要使用特定端口。你可以简单地省略端口(或使用 0
),操作系统将自动为你选择一个任意未使用的端口:
¥When testing, you might not need to use a specific port. You can simply omit the port (or use 0
) and the operating system will automatically pick an arbitrary unused port for you:
- CommonJS
- ES modules
- 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;
// ...
});