Using any technique, is it possible to keep the websocket connected when restarting Node.js server?
No, not directly. By design, an OS cleans up any resources owned by a process when that process shuts-down. This is how the OS prevents resource leaks over time as processes start up and shut down. So, when your server process shuts down, any sockets it still has open will get shut down by the OS.
The usual design solution for this is to code clients that automatically reconnect if they lose their webSocket connection when the client didn't intend to lose the connection. This type of auto-reconnect behavior is built into socket.io (a layer that sits on top of webSocket) for this exact reason.
If you insert a proxy in front of your server, configured so that clients connect to the proxy and then the proxy then connects through to your server, then it might be possible to teach the proxy to auto-reconnect to the server in a way that the clients would not know anything had happened (as long as they didn't try to send messages while the server was down). Of course, then you have the same restart issue with the proxy.
In some operating systems, it is possible to transfer ownership of TCP sockets from one process on the same host to another process. So, I could conceive of a scheme (which I have not tried) where you could fire up a temporary process, transfer all the webSocket sockets from your server to this temporary process, then restart your server, then after the new server instance comes up, transfer the sockets back and then kill the temporary process.
Since there are multiple other reasons why a webSocket might be unintentionally disconnected, I think the client-side reconnect is a solution that covers both the server restart and many other potential things that could happen in your system and for which code has already been written.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With