简体   繁体   中英

Handling Node.js server restart on the client

I am building a multiplayer card game using a Node.js back-end with socket.io for bi-directional client-server communication.

I have come to the last phase of the project, and I need to add some fail-safes for server crashes (for whichever reason they may happen). So, I'm using PM2 ( Git here ) to keep the server process alive, that is, restart it automatically whenever it crashes. This works fine as far as restarting the server goes (and reloading live game data, but that's another story). However, I'm having trouble communicating the server crash to the currently connected clients.

For instance, when a client is connected to a game room and the server crashes, then clicking a card to play does nothing anymore - even after the server restarts. So the visitor is left wondering what's going on. Here are some ideas I've had but I keep running into different walls:

1) When the server crashes, emit a message to all connected clients to let them know. But, since the server has restarted, none of the clients are actually connected to it anymore, so the client list is empty at this point.

2) When a client tries to send data to the server (such as playing a card), check if the server is online and let them know if not. I tried using the following code to check if the io object (connection object for socket.io) is defined, but it always returns true:

var isIOLoaded = function(){
    return (typeof(io) != "undefined") ? true : false;
}

I think this is the io object for the previous server instance, before the restart.

Bottom line - the client needs to have a way of checking if they are still connected to the server and, if not, try connecting again. How can I accomplish this?

You could use socket.on('disconnect', function () {}) on client to detect when server doesn't respond any more.

Also socket.io supports auto reconnect, so you could use socket.on('connect', function () {}} on client to detect when client restores connection, and develop logic to restore client.

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