Grufkork Grufkork - 5 months ago 29
Javascript Question

Check if socket.io server is online from client

I am trying to make a simple socket.io game. I have a login screen, where you enter your username and password, and then you click a big connect button and then you're in (if the client manages to connect to the server). I would like to have a status box on the login screen, so you can see if the server is up or down. I am wondering if there is some sort of ping function in socket.io. Otherwise, could you try to connect to the server (for example, I don't know what's good) 4 times. If it fails, it calls a function/sets a variable, whatever. If it succeeds it calls a function or something, then it disconnects. I have googled around a bit, but can't find anything. (By the way, sorry if this is really noobish, and there is a really apparent solution. I'm new to socket.io

Answer

Socket io has an event listener for this situation. Reconnecting event will fire when socket.io tries to connect but fails. Its a bit misleading cuz it won't fire on every reconnect just when the reconnect try fails.

socket.on('reconnecting', function reconnectCallback(tries) {
    if (tries === 3) {
         //handle your offline mode here
    }
});

socket.on('connect', function connectCallback() {
    //handle successful connection here then disconnect
    socket.disconnect();
});