viablepath
viablepath

Reputation: 307

Pool Websocket Connections - NodeJS

I'm looking to build a node app that will accomplish the following:

  1. Open several websocket connections, almost as if each of them were a thread
  2. Allow each websocket to have a unique/dynamic URL
  3. Create a pool of websocket connections in an object based off some kind of DB query (so I can dynamically add/remove connections)

I've decided to use the ws library (https://github.com/websockets/ws) since its the fastest and least bloated option available. I currently have the following function, which only supports a single ws connection:

chat.prototype.connect = function() {
var self = this;
  self.ws = new ws(url);
  self.ws.on('message', function(data, flags) {
    var message = JSON.parse(data);
    self.handle(message);
  });
};

This code listens to a single websocket URL and passes the message(s) to my handler to process the message. Instead, I want to make this function listen to multiple (potentially hundreds) of websocket URL's.

Does anyone have some ideas on how to accomplish this?

Upvotes: 1

Views: 2122

Answers (1)

robertklep
robertklep

Reputation: 203231

Say that you have the list of url's you need to connect to stored in an instance property called urls. You could set up the connections like this:

chat.prototype.connect = function() {
  urls.forEach(this.connectOne.bind(this));
};

chat.prototype.connectOne = function(url) {
  var handle = this.handle.bind(this);
  var conn   = this.connections[url] = new ws(url);
  conn.on('message', function(data, flags) {
    var message = JSON.parse(data);
    handle(message);
  });
};

To implement adding new connections, periodically query your database and check if each URL is already present in this.connections; if not, you can use this.connectOne() to add it. You'd do something similar to remove a connection.

Upvotes: 2

Related Questions