NodeJS 测试套接字是否打开并侦听,节点,socket.io

pbpqsu0x  于 2023-08-04  发布在  Node.js
关注(0)|答案(1)|浏览(117)

我想知道一个独立的Node应用程序是否有一个远程服务器(运行在Socket.io上)正在监听传入的连接。
如果服务器已启动并正在侦听,则使用socket-io.client进行连接,如果没有,则将某些内容记录到数据库中。
我不知道如何用socket-io. client来完成这个任务。地址有IP和端口,所以我不能ping到没有端口的IP。
有什么想法吗?谢谢!

eeq64g8w

eeq64g8w1#

您可以尝试创建一个socket.io连接到服务器。如果它成功了,那么它就是在倾听。如果它失败了,那么显然它没有在听。这里有一个方法可以做到这一点:

// check a socket.io connection on another server from a node.js server
// can also by used from browser client by removing the require()
// pass hostname and port in URL form
// if no port, then default is 80 for http and 443 for https
// 2nd argument timeout is optional, defaults to 5 seconds
var io = require('socket.io-client');

function checkSocketIoConnect(url, timeout) {
    return new Promise(function(resolve, reject) {
        var errAlready = false;
        timeout = timeout || 5000;
        var socket = io(url, {reconnection: false, timeout: timeout});
        
        // success
        socket.on("connect", function() {
            clearTimeout(timer);
            resolve();
            socket.close();
        });
        
        // set our own timeout in case the socket ends some other way than what we are listening for
        var timer = setTimeout(function() {
            timer = null;
            error("local timeout");
        }, timeout);
        
        // common error handler
        function error(data) {
            if (timer) {
                clearTimeout(timer);
                timer = null;
            }
            if (!errAlready) {
                errAlready = true;
                reject(data);
                socket.disconnect();
            }
        }
        
        // errors
        socket.on("connect_error", error);
        socket.on("connect_timeout", error);
        socket.on("error", error);
        socket.on("disconnect", error);
        
    });
}

checkSocketIoConnect("http://192.168.1.10:8080").then(function() {
    // succeeded here
}, function(reason) {
    // failed here
});

字符串

相关问题