如果远程服务器(使用Socket.io运行)启动并侦听传入连接,我想知道构建一个独立的节点应用程序。
如果服务器已启动并正在侦听,则使用socket-io.client连接,如果没有,则将某些内容记录到数据库中。
我不知道如何使用socket-io.client完成此任务。地址有IP和端口,所以我只能在没有端口的情况下ping到IP。
有什么想法吗?谢谢!
答案 0 :(得分:3)
您可以尝试与服务器建立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 447 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
});