未捕获的异常:绑定 EADDRINUSE,但未找到使用该端口的进程

Uncaught Exception: bind EADDRINUSE, but no process is found using that port

我正在构建一个使用端口的 Node.js 应用程序。关闭应用程序并再次打开后,出现此错误:

Uncaught Exception:
Error: bind EADDRINUSE 0.0.0.0:20802
    at _handle.lookup (dgram.js:282:18)
    at process._tickCallback (internal/process/next_tick.js:63:19)

当然,我在网上查了一下,我看到我应该运行命令sudo lsof -t -i tcp:20802,我试过lsof -i:20802,我也试过sudo kill $(sudo lsof -t -i:20802)到[=32] =] 正在使用该端口的进程没有成功。奇怪的是没有找到进程。我用几个工具试了好几遍,好像这个端口真的没有被任何应用程序使用。

每次我关闭应用程序时,我都有一个执行 client.stop() 的侦听器,因此,当退出应用程序时,我不应该打开任何端口。

如有任何帮助,我们将不胜感激。

编辑:当 运行ning dgram 的 .bind() 时失败,我什至尝试在与库绑定之前释放端口(kill-port),但它仍然失败。请检查附件中的图片。

您需要使用 exclusive: false 绑定到套接字。驱动程序级别的底层 TCP 堆栈支持套接字选项 SO_REUSEADDRSO_REUSEPORT(有关更多详细信息,请参见手册页)。例如,这是为了支持在服务器实现中重新绑定到同一端口。

来自节点文档:

The options object may contain an additional exclusive property that is used when using dgram.Socket objects with the cluster module. When exclusive is set to false (the default), cluster workers will use the same underlying socket handle allowing connection handling duties to be shared. When exclusive is true, however, the handle is not shared and attempted port sharing results in an error.

socket.bind({
  address: 'localhost',
  port: 8000,
  exclusive: false
});

更新:

使用 dgram.createSocket(options[, callback]) 创建套接字并按照描述设置选项

reuseAddr When true socket.bind() will reuse the address, even if another process has already bound a socket on it. Default: false.

参考文献: