socket.io-routr

1.0.0 • Public • Published

socket.io-routr

A socket.io router based on http-proxy to handle multiple socket.io servers.

Installation

$ npm install socket.io-routr

How to use

const createRouter = require('socket.io-routr');
const Client = require("socket.io-client");
const redis = require('redis');
 
const redisClient = redis.createClient(6379, 'localhost');
 
const router = createRouter(
  redisClient,
  [
    new Client('http://localhost:3000'),
    new Client('http://localhost:3001'),
    new Client('http://localhost:3002'),
  ]
);
 
const port = process.env['PORT'] || 4000;
 
router.listen(port, () => {
  console.log(`router listening on port ${port}`);
});

Options:

  • path: the name of the path to capture (optional, defaulting to /socket.io/)
  • keyPrefix: the prefix to use for the keys stored in Redis (optional, defaulting to socket.io#)
  • keyExpiry: the TTL in seconds of the keys stored in Redis (optional, defaulting to 60)

How it works

The polling transport requires that every request is directed to the same backend for the duration of the session. There are several ways to meet this requirement:

  • only use the websocket transport, but in that case you should rather consider using something like robust-websocket for the client and ws for the server, as one of the main features of Socket.IO is to provide a fallback when WebSocket connection is not possible.

  • use sticky-session, either IP-based (NGINX example) or cookie-based (HAProxy example, HTTPD example)

  • use Fedor Indutny's sticky-session package in a cluster environment

  • or try this package:

On first request (the socket has no id yet), the request is proxied to a random available backend. The id is sent as part of the response, which the proxy reads to save the association in Redis (key: <keyPrefix><socket id> with an expiry of <keyExpiry> seconds).

For the next requests or the WebSocket upgrade, the association is retrieved from Redis and the request is proxied to the right backend.

Debug

The package uses debug. In order to see all the debug output, you can run the proxy with the environment variable DEBUG including the desired scope:

$ DEBUG=socket.io-routr* node index

Readme

Keywords

none

Package Sidebar

Install

npm i socket.io-routr

Weekly Downloads

1

Version

1.0.0

License

MIT

Last publish

Collaborators

  • darrachequesne