D
D
devekipers2021-07-22 12:30:42
Node.js
devekipers, 2021-07-22 12:30:42

Add WebSocket reconnect?

How to implement automatic reconnection to a websocket if the connection drops?

'use strict'

const fs = require('fs')
const https = require('https')
const WebSocketServer = require('ws').Server
const url = require('url')

const key = fs.readFileSync('/var/www/www-root/data/www/comfortapp.online/ws/server/key.pem', 'utf8')
const certificate = fs.readFileSync('/var/www/www-root/data/www/comfortapp.online/ws/server/certificate.pem', 'utf8')

const server = https.createServer({ key, cert: certificate })

const wssControllers = new WebSocketServer({ noServer: true })
const wssDisplays = new WebSocketServer({ noServer: true })

const onUpgrade = (request, socket, head) => {
  const pathname = url.parse(request.url).pathname

  if (pathname === '/' || pathname === '/app') {
    wssControllers.handleUpgrade(request, socket, head, (ws) => wssControllers.emit('connection', ws, request))
  } else if (pathname === '/main') {
    wssDisplays.handleUpgrade(request, socket, head, (ws) => wssDisplays.emit('connection', ws, request))
  } else {
    socket.destroy()
  }
}

const onControllersConnection = (connection) => {
  connection.on('message', onControllerMessage)
}

const onControllerMessage = (message) => {
  try {
    const data = JSON.parse(message)
    if (!data.method) data.method = 'showImage'
    message = JSON.stringify(data)
  } catch (e) {

  }

  for (const client of wssDisplays.clients) {
    client.send(message)
  }
}

wssControllers.on('connection', onControllersConnection)

server.on('upgrade', onUpgrade)
server.listen(3301, '0.0.0.0')

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
aagzip, 2021-07-22
@aagzip

For example like this:

function connect() {
  var ws = new WebSocket('ws://localhost:8080');
  ws.onopen = function() {
    // subscribe to some channels
    ws.send(JSON.stringify({
        //.... some message the I must send when I connect ....
    }));
  };

  ws.onmessage = function(e) {
    console.log('Message:', e.data);
  };

  ws.onclose = function(e) {
    console.log('Socket is closed. Reconnect will be attempted in 1 second.', e.reason);
    setTimeout(function() {
      connect();
    }, 1000);
  };

  ws.onerror = function(err) {
    console.error('Socket encountered error: ', err.message, 'Closing socket');
    ws.close();
  };
}

connect();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question