Search code examples
node.jsexpressws

How to spin up a websocket server paralelly along with express app?


I have an express application, and a websocket script. I create the server and spinup the express app in a www.js file.

The problem I'm facing is that, I'm not able to instantiate the websocket inside the www.js file.

Here is the www.js

....
const server = http.createServer(app);
server.listen(port);
server.on("error", onError);
server.on("listening", onListening);
....

Here is the websocket.js

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function connection(ws) {
  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
  });

  ws.send('something');
});

I know the line const wss = new Websocket.Server({ port: 8080 }); creates the websocket instance...but I want to be able to create this instance in www.js file and all the logic for websocket in a seperate file.


Solution

  • Pass the http server instance to the websocket server,

    const wss = new Websocket.Server({ server: server });
    

    If you want to separate it as a single modules to a file,

    const WebSocket = require('ws');
    
    
    const initWSServer = (server) => {
      const wss = new WebSocket.Server({ server: server});
    
      wss.on('connection', function connection(ws) {
    
        ws.on('message', function incoming(message) {
          console.log('received: %s', message);
        });
    
        ws.send('something');
    
      });
    }
    
    module.exports = {
      initWSServer
    }
    

    Then,

    const server = http.createServer(app);
    server.listen(port);
    server.on("error", onError);
    server.on("listening", onListening);
    
    const ws_server = require('./websocket.js');
    ws_server.initWSServer(server);