简体   繁体   中英

Client-side event when Node server comes online

In my client-side node code, I have something like this:

var socket = io('//localhost:1337');

$(function() {
    if ( !socket.connected )
        NodeOfflineError();
});

Now, let's say I had a NodeBackOnlineAlert() function to go along with the NodeOfflineError() function, how would I know when to call it?

Is there a listener for the polling that checks whether the server is live?

You can use the listener events of socket io (assuming you use socket io)

const socket = io('//localhost:1337')
$(() => {
    socket.on('connected', socket => {
        console.log('connected!')

        socket.on('disconnect', () => {
            NodeOfflineError()
        })
    })

    socket.on('reconnect', () => {
        NodeBackOnlineAlert()
    })
})

http://socket.io/docs/ Check the part where it says 'Sending and receiving events' also http://socket.io/docs/client-api/ :)

You can have listeners that run the function and have a function to reconnect when the socket is disconnected:

socket.on("disconnect", function() {
                    NodeOfflineError();
                    socket.socket.reconnect();

                });

socket.on("connect", function() {
                NodeOnlineAlert()
                });

socket.on("reconnect", function() {
                NodeBackOnlineAlert()
                });

You could use Server Sent Events: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events . The MDN guide should have everything you need to implement them (they're quite simple!). This library might prove useful for your server: https://www.npmjs.com/package/sse

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