0

I am trying to somehow have some separation of my WS code in my node/express. I want to have some routes in my WS code, like the API routes that express has. I am using the ws module

I guess I could use something out of the box like express-ws, but is there a way to do this without using any extra npm module? I dont want to deploy another module because less modules means a more minimal and easy to maintain project. Also, if I do this without a module I will better understand how WS work.

I guess I could put some parts of the WS in a separate js file, export it and then include it in my app.js. But do I also need to import WS in that file, since I need the .on('something' events?

broadcast.js file
 //include 
const  broadcast = (wss) =>{
  var broadcast = function() { 
      var jsonmsg = JSON.stringify({
      message: 'hello'
  });

  // wss.clients is an array of all connected clients
  wss.clients.forEach(function each(client) {
      client.send(jsonmsg);
      console.log('Sent: ' + jsonmsg);
    });
  }
} 

exports.broadcast = broadcast;


and then use it like
const bc = require('./broadcast.js');
bc.broadcast(wss);

By separating the WS layer, I could also use WS routes, to have different endpoints for different tasks. How can I create WS routes? I can maybe work with the path of the ws module ?

var wss = new wsserver({ port: 5001 , path: "/flip"})

and move the code for flip to another file? I am not sure how to do this and based on a little testing I did, the same WS port does not support multiple paths

Thanks

codebot
  • 517
  • 8
  • 29
  • 55
  • Possible duplicate of [How to setup route for websocket server in express?](https://stackoverflow.com/questions/22429744/how-to-setup-route-for-websocket-server-in-express) – 1565986223 Aug 27 '19 at 15:55
  • @codebot, if you're still having this problem (2 years later), I've posted a working solution here: https://stackoverflow.com/questions/69773285/defining-websocket-routes-for-express/69773286#69773286 – Nerdragen Oct 29 '21 at 18:40

0 Answers0