如何在 NodeJS 中检查端口是否繁忙?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19129570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I check if port is busy in NodeJS?
提问by Ionic? Biz?u
How can I check if port is busyfor localhost?
如何检查,如果端口忙的localhost?
Is there any standard algorithm? I am thinking at making a httprequest to that url and check if response status code is not 404.
有标准算法吗?我正在考虑http向该 url发出请求并检查响应状态代码是否不是404.
回答by hexacyanide
You could attempt to start a server, either TCP or HTTP, it doesn't matter. Then you could try to start listening on a port, and if it fails, check if the error code is EADDRINUSE.
您可以尝试启动服务器,无论是 TCP 还是 HTTP,都没有关系。然后你可以尝试开始监听某个端口,如果失败,检查错误代码是否为EADDRINUSE。
var net = require('net');
var server = net.createServer();
server.once('error', function(err) {
if (err.code === 'EADDRINUSE') {
// port is currently in use
}
});
server.once('listening', function() {
// close the server if listening doesn't fail
server.close();
});
server.listen(/* put the port to check here */);
With the single-use event handlers, you could wrap this into an asynchronous check function.
使用一次性事件处理程序,您可以将其包装到异步检查函数中。
回答by Codebling
Check out the amazing tcp-port-used node module!
查看惊人的tcp-port-used 节点模块!
//Check if a port is open
tcpPortUsed.check(port [, host])
//Wait until a port is no longer being used
tcpPortUsed.waitUntilFree(port [, retryTimeMs] [, timeOutMs])
//Wait until a port is accepting connections
tcpPortUsed.waitUntilUsed(port [, retryTimeMs] [, timeOutMs])
//and a few others!
I've used these to great effect with my gulpwatchtasks for detecting when my Express server has been safely terminated and when it has spun up again.
我已经在我的gulpwatch任务中使用了这些,用于检测我的 Express 服务器何时安全终止以及何时再次启动。
This will accurately report whether a port is bound or not (regardless of SO_REUSEADDRand SO_REUSEPORT, as mentioned by @StevenVachon).
这将准确报告端口是否已绑定(不管SO_REUSEADDR和SO_REUSEPORT,如@StevenVachon 所述)。
The portscanner NPM modulewill find free and used ports for you within ranges and is more useful if you're trying to find an open port to bind.
在端口扫描工具NPM模块会发现免费使用的端口为你的范围内,如果你想找到一个打开的端口绑定是比较有用的。

