RafalWilinski/express-status-monitor

Multiple websocket

ran-j opened this issue · 1 comments

ran-j commented

In my app I'm alread use websocket, there is a way to set a path or change port to connect to this framework ?

You can specify the path and/or port for the socket.io server so that it does not interfere with your existing websocket.

const statusMonitor = require('express-status-monitor')({ path: '/secret' });
app.use(statusMonitor);
const statusMonitor = require('express-status-monitor')({ port: 5000 });
app.use(statusMonitor);
const statusMonitor = require('express-status-monitor')({ path: '/secret', port: 5000 });
app.use(statusMonitor);

If you need socket.io and websocket to be on the same port, you would need to handle the protocol upgrade manually.

// setting up express
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
app.get('/', (req, res) => {
  res.send('<h1>Hello world</h1>');
});
server.listen(3000, () => {
  console.log('listening on *:3000');
});

// using express-status-monitor (which sets up a socket.io server automatically)
app.use(require('express-status-monitor')({ path: '/mySecretPath' }));

// retrieve and disable upgrade handler (for socket.io server)
const ioHandleUpgrade = server._events.upgrade;
server.off('upgrade', ioHandleUpgrade);

// create your websocket server
const WebSocket = require('ws');
const wsServer = new WebSocket.Server({ noServer: true });

// override the upgrade handler, depending on req.url, route either to socket.io or websocket
server.on('upgrade', function(req, socket, head) {
  if (req.url.startsWith('/mySecretPath')) { // the same path as express-status-monitor options
    ioHandleUpgrade(req, socket, head);
  } else {
    wsServer.handleUpgrade(req, socket, head, (webSocket) => {
      wsServer.emit('connection', webSocket, req);
    });
  }
});