Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create multiple Node.js websockets on relative path

Tags:

node.js

For example, if I want to run:

var http = require('http');
var s = http.createServer();
var WebSocket = require('ws');
var WebSocketServer = WebSocket.Server;
s.on('request', (request, response)=>{
// other codes
});
s.listen(process.env.PORT || 3000);
var a = new WebSocketServer('/a');
var b = new WebSocketServer('/b');
var c = new WebSocketServer('/c');

So ideally I want a to be process.env.host:process.env.PORT/a, likewise for b and c. How will this be done? What's the correct syntax?

like image 295
Aero Wang Avatar asked Sep 05 '26 08:09

Aero Wang


1 Answers

You can't have multiple servers on the same port. You can implement one webSocket server and then route the incoming requests based on the incoming URL to different code. That should be all you need.

const WebSocket = require('ws');

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

wss.on('connection', function connection(ws, req) {
    const location = url.parse(req.url, true);
    // branch your code here based on location.pathname
});

If you want to be able to broadcast separately to each group based on their original path, then you can implement collections of connected sockets based upon the incoming path so you can broadcast to all in any particular connection.

If you're going to keep wanting more features like this, then perhaps you should use socket.io instead which has rooms and namespaces already built-in which does both of these for you.

like image 60
jfriend00 Avatar answered Sep 06 '26 21:09

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!