简体   繁体   English

Socket.io客户端火灾事件如果无法连接到服务器

[英]Socket.io Client Fire Event if Can't connect to server

I'm running a simple node.js server on Amazon EC2 that is running socket.io for me. 我正在运行socket.io的Amazon EC2上运行一个简单的node.js服务器。 I'm working on a chrome extension that sends data between two clients. 我正在研究一个在两个客户端之间发送数据的chrome扩展。 However, if I take the server offline, the clients don't attempt to reconnect automatically. 但是,如果我使服务器脱机,则客户端不会尝试自动重新连接。 I would like to implement this feature. 我想实现这个功能。 When I do socket = io.connect("http://xxx.xxx.xxx.xxx:xxx") if it can't find the server at the specified IP address and port, how do I get it to fire an event that makes it go into a recursive loop until it can? 当我执行socket = io.connect("http://xxx.xxx.xxx.xxx:xxx")如果它找不到指定IP地址和端口的服务器时,如何让它触发事件这使它进入递归循环,直到它可以? Does something like this exist? 这样的事情存在吗?

function connect() {
    socket = io.connect("http://123.456.789.1011:1337");
    socket.on('server_not_found', function() {
        connect();
    });
}

From the socket.io wiki it looks like there is a connect_failed event that you can listen to ( https://github.com/LearnBoost/socket.io/wiki/Exposed-events ). 从socket.io wiki看起来有一个你可以收听的connect_failed事件( https://github.com/LearnBoost/socket.io/wiki/Exposed-events )。 That event did not fire for me (see https://github.com/LearnBoost/socket.io-client/issues/375 ) but the error event will fire if the connection fails and you can check the connection status on the socket. 那个事件并不适合我(请参阅https://github.com/LearnBoost/socket.io-client/issues/375 )但如果​​连接失败,则会触发错误事件,您可以检查套接字上的连接状态。 You could try either and see what works better. 你可以尝试任何一种,看看哪种效果更好。

An example might look like: 示例可能如下所示:

function connect() {
    var socket = io.connect("http://123.456.789.1011:1337"),
        timer;

    socket.on('error', function() {
        // wait 5 seconds then try again
        if (!socket.socket.connected) {
            timer = window.setInterval(function() { connect() }, 5000);
        }
    });

    socket.on('connect', function() {
        // we've connected so clear the timer
        window.clearInterval(timer);
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM