简体   繁体   中英

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. I'm working on a chrome extension that sends data between two clients. 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? 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 ). 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. 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);
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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