Ws: Multi room chat

Created on 23 Apr 2017  路  3Comments  路  Source: websockets/ws

How to implement multi room chat based on ws? I see function wss.clients.forEach but it sends messages to all users.

Most helpful comment

There is a nice better approach for this purposes. Based on upgradeReq.url filtering. Just like ws-broadcast.js have implented.
https://github.com/maxleiko/ws-broadcast/blob/master/lib/wsClientHandler.js

client.on('message', function (msg) {
// broadcast message to all connected clients in the room
wss.clients.forEach(function (c) {
if (c.upgradeReq.url === client.upgradeReq.url && c.id !== client.id) {
if (c && c.readyState === WebSocket.OPEN) {
c.send(msg);
}
}
});
});
So it is much naturally for a multi user webrtc app.

All 3 comments

You have to group connections in "rooms". There is no built-in way to achieve this as it's out of the scope of this module.
You can use higher level modules like primus or socket.io or build your own solution.

Here we go. Proof of concept.

const WebSocket = require('ws');
const http=require('http');

const express = require('express');
const app = express();

app.use(express.static('public'));
const bserver=http.createServer(app);
const webPort = 5000;

bserver.listen(webPort, function(){
console.log('Web server start. http://localhost:' + webPort );
});
const wss=new WebSocket.Server({server:bserver});

wss.on('connection',ws=>{
ws.room=[];
ws.send(JSON.stringify({msg:"user joined"}));
console.log('connected');
ws.on('message', message=>{
console.log('message: ',message);
//try{
var messag=JSON.parse(message);
//}catch(e){console.log(e)}
if(messag.join){ws.room.push(messag.join)}
if(messag.room){broadcast(message);}
if(messag.msg){console.log('message: ',messag.msg)}
})

ws.on('error',e=>console.log(e))
ws.on('close',(e)=>console.log('websocket closed'+e))

})

function broadcast(message){
wss.clients.forEach(client=>{
if(client.room.indexOf(JSON.parse(message).room)>-1){
client.send(message)
}
})
}

https://gist.github.com/Globik/5a63e8683ab1d1c2c72fd25a798ae2d8

There is a nice better approach for this purposes. Based on upgradeReq.url filtering. Just like ws-broadcast.js have implented.
https://github.com/maxleiko/ws-broadcast/blob/master/lib/wsClientHandler.js

client.on('message', function (msg) {
// broadcast message to all connected clients in the room
wss.clients.forEach(function (c) {
if (c.upgradeReq.url === client.upgradeReq.url && c.id !== client.id) {
if (c && c.readyState === WebSocket.OPEN) {
c.send(msg);
}
}
});
});
So it is much naturally for a multi user webrtc app.

Was this page helpful?
0 / 5 - 0 ratings