D
D
DanKud2017-03-01 16:26:12
JavaScript
DanKud, 2017-03-01 16:26:12

How to make automatic reconnection to websocket server?

From time to time, the websocket server drops the connection. How to make automatic reconnection to the server at each disconnect in this code? What should be added to function close()?

const WebSocket = require('ws');

const ws = new WebSocket('ws://serveradress.com', {
});

ws.on('open', function open() {
  console.log('connected');
  ws.send('sendmessage');
});

ws.on('close', function close() {
  console.log('disconnected');
});

ws.on('message', function incoming(data) {
  console.log(data);
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene Khrustalev, 2017-03-01
@eugenehr

Wrap all code in a separate connect function and call it from ws.on('close', connect)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question