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?
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).