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 = ;const Client = ;const redis = ; const redisClient = redis; const router = ; const port = processenv'PORT' || 4000; router;
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