1

Example:

var WebSocket = require('ws');
var ws = new WebSocket('ws://echo.websocket.org/', {protocolVersion: 8, origin: 'http://websocket.org'});
ws.on('open', function() {
    console.log('connected');
    ws.send(Date.now().toString(), {mask: true});
});
ws.on('close', function() {
    console.log('disconnected');
    // What do I do here to reconnect?
});

What should I do when the socket closes to reconnect to the server?

user2864740
  • 60,010
  • 15
  • 145
  • 220
samol
  • 18,950
  • 32
  • 88
  • 127
  • If I remember correctly sockets try to reconnect upon disconnection – Sterling Archer Jul 30 '14 at 21:38
  • @SterlingArcher unfortunately, it does not actually do that – samol Jul 30 '14 at 22:35
  • A robust solution isn't too terrible but it's not exactly a 5 line patch either. Here's one solution. https://github.com/joewalnes/reconnecting-websocket/blob/master/reconnecting-websocket.js#L124 – aembke Jul 30 '14 at 23:01
  • @aembke: joewalnes' project has been [abandoned](https://github.com/joewalnes/reconnecting-websocket/issues) for over a year and it's unclear if it targets node or the browser. – Dan Dascalescu Jan 11 '18 at 23:57
  • Duplicate of [NodeJS Websocket how to reconnect when server restarts](https://stackoverflow.com/questions/19691996/nodejs-websocket-how-to-reconnect-when-server-restarts) – Dan Dascalescu Jan 11 '18 at 23:58

1 Answers1

1

You can wrap all your setup in a function and then call it from the close handler:

var WebSocket = require('ws');
var openWebSocket = function() {
    var ws = new WebSocket('ws://echo.websocket.org/', {protocolVersion: 8, origin: 'http://websocket.org'});
    ws.on('open', function() {
        console.log('connected');
        ws.send(Date.now().toString(), {mask: true});
    });
    ws.on('close', function() {
        console.log('disconnected');
        openWebSocket();
    });
}
openWebSocket();

However, there is likely more logic you want here (what if the close was on purpose? what happens if you try to send a message while its reconnecting?). You're probably better off using a library. This library suggested by aembke in the comments seems reasonable. socket.io is not a bad choice (and it gives you non-WebSocket transports).

Aaron Dufour
  • 17,288
  • 1
  • 47
  • 69