0

In nodejs how to connect to multiple endpoints based on the comma separated endpoint values. I am using the library https://www.npmjs.com/package/websocket. From a single client I am able to connect but I am not getting how to connect to multiple endpoints. Below is the code for single websocket connection.

const WebSocket = require('ws');

const ws = new WebSocket('wss://echo.websocket.org');

ws.on('open', function open() {
  ws.send('something');
});

ws.on('message', function incoming(data) {
  console.log(data);
});
Romi Halasz
  • 1,949
  • 1
  • 13
  • 23
ashok
  • 1,078
  • 3
  • 20
  • 63

1 Answers1

2

You can use an array to store connections to multiple sockets. This might be an idea:

const WebSocket = require('ws');

const urls = ['wss://echo.websocket.org'];
let connections = [];

urls.map( function(url) {
  const ws = new WebSocket(url);

  ws.on('open', function open() {
    ws.send('something');
  });

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

  connections.push(ws);
});

The connections array will store all the connections, but you can't have a single socket object connect to multiple endpoints.

Hope you find this helpful.

Romi Halasz
  • 1,949
  • 1
  • 13
  • 23
  • Thank you!! how can I reconnect – ashok Feb 06 '20 at 11:02
  • 1
    @vikram I think you may find an answer to that here : https://stackoverflow.com/questions/22431751/websocket-how-to-automatically-reconnect-after-it-dies – Seblor Feb 06 '20 at 11:20
  • Thank you, actually I am reading the endpoints from redis every n minutes. I wanted to add url dynamically after reading and if the endpoint already exists ignore for new connection, if the new list got from redis doesnt has endpoint which is already connected then it should disconnect that endpoint. How can I do this Ijust want to modify the connected endpoint to be disonnected or add a new connection. – ashok Feb 06 '20 at 19:27