简体   繁体   中英

Websocket availability using socketio

I'm trying to detect whether the websocket is running before allowing clients to connect to it. Consider the following code:

var socket = io.connect('1.1.1.1:1234');
        socket.on('connect',function() {
            console.log('Client has connected to the server');
        });

        socket.on('disconnect',function() {
            console.log("The client has disconnected from the server");
        });

How can I make sure that this block is only called if the server on that IP is actually running and how can I output a message to the users stating that the server is not up?

Thank you

You would need to fire the io.connect() atleast once (consider this as a ping) to detect if server is up, but you can then handle the failure to connect with the socket.on('connect_failed', function () {}) event handler and show a message to user that the 'server is down'.
Have a look at Exposed Events for the client

Further, if you would want to reduce the number of times the reconnect is attempted, you can change the socket.io configuration setting for 'reconnect' to false.
Checkout Socket.io Configuration for more details

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