确定服务器是否已经在侦听 unix 域套接字的路径 [英] Determine if server is already listening on path to unix domain socket
本文介绍了确定服务器是否已经在侦听 unix 域套接字的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Node.js 版本 10+ 上
On Node.js version 10+
假设我们有一个服务器在监听一个路径(unix 域套接字):
Say we have a server listening on a path (unix domain sockets):
const server = net.createServer(socket => {
});
const p = path.resolve(process.env.HOME + '/unix.sock');
server.listen(p);
在运行上述代码之前,有没有办法确定其他服务器是否已经在侦听路径 p?
is there a way to determine if some other server is already listening on path p, before running the above code?
推荐答案
我现有的答案的替代方案是创建客户端并尝试连接到服务器.根据结果可以判断是否占用了unix socket.
An alternative to my existing answer would be creating a client and trying to connect to the server. Based on the result, you can identify whether the unix socket is taken or not.
function isPortTaken(port, fn) {
var net = require('net');
var client = new net.Socket();
client.connect(port, function(err) {
if(err)
return fn(false)
client.destroy();
fn(true);
});
}
警告:如果服务器在新连接上触发某些操作,这将触发它.
Warning: In case the server triggers some action on a new connection, this will trigger it.
这篇关于确定服务器是否已经在侦听 unix 域套接字的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文