Home > database >  node ws package, seperate connections into rooms
node ws package, seperate connections into rooms

Time:02-20

I am trying to create a "rooms" like feature with the npm 'ws' package, similar to how rooms work in socket.io. I dont want to use socket.io, but cant figure out how to get information on the user/room at connection without sending an extra message.

I took this from the ws docs and it allows me to iterate through all the clients, but i would like to also differentiate a room?

import WebSocket, { WebSocketServer } from 'ws';

const wss = new WebSocketServer({ port: 8080 });

wss.on('connection', function connection(ws) {
  // would like to add a user to a room here?
  ws.on('message', function message(data) {
    wss.clients.forEach(function each(client) {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        // only send to clients in the same room
      }
    });
  });
});

This is the client side I have been using to test:

import WebSocket from 'ws';

const ws = new WebSocket('ws://localhost:8080');

ws.on('open', function open() {
  ws.send(JSON.stringify({roomId: 1}));
});

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

CodePudding user response:

If you are wanting to assign a room at connection you change the path of the url and then access it through the req object, then add it as a property on the connecting websocket.

Then you can send the roomId with any message and check that the roomId for message and the roomId for the client match before sending.

wss.on('connection', function connection(ws, req) {
  ws.roomId = req.url;
  ws.on('message', function message(data) {
    const parsedMessage = JSON.parse(data);
    wss.clients.forEach(function each(client) {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        if(client.roomId === parsedMessage.roomId){
          ws.send(data);
        }
      }
    });
  });
});

In order to connect to this socket you would have to change your client to send to the url the roomId.

const ws = new WebSocket('ws://localhost:8080/<put room id here>');

Without sending a second message this appears to get the functionality you are looking for

  • Related