Lae*_*ion 1 sockets node.js socket.io
如果远程服务器(使用 Socket.io 运行)启动并侦听传入连接,我想知道形成一个独立的 Node 应用程序。
如果服务器已启动并正在侦听,则使用 socket-io.client 连接,如果没有,则将某些内容记录到数据库中。
我不知道如何使用 socket-io.client 完成此操作。该地址有 IP 和端口,所以我不能在没有端口的情况下 ping 到 IP。
有任何想法吗?谢谢!
您可以尝试与服务器建立 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
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4941 次 |
| 最近记录: |