Closed genezablan closed 8 years ago
Hi again,
Yeah, it should be fairly trivial to extend my previous example to also include a count of online users for each channel.
Something along these lines should work:
var chatrooms = {};
app.ws('/chatroom/:name', function(ws, req) {
var name = req.params.name;
var room = chatrooms[name] || {
connections: []
};
room.connections.push(ws);
chatrooms[name] = room;
ws.on('message', function(msg) {
room.connections.forEach(function(conn) {
if (conn === ws) return;
conn.send(msg);
});
});
ws.on('close', function() {
var idx = room.connections.indexOf(ws);
if (idx !== -1) {
room.connections.splice(idx, 1);
}
});
});
app.get('/chatroom/:name', function(req, res) {
var connections = 0;
var room = chatrooms[req.params.name];
if (room) {
connections = room.connections.length;
}
res.send({ connections: connections });
});
Hi im new to express ws is there a way on how can i get the online users
var chatrooms = {};
app.ws('/send/:chatroom_id', function(ws,req,next) { var chatroom_id = req.chatroom_id; var room = chatrooms[chatroom_id] || { connections : [] }; room.connections.push(ws); chatrooms[chatroom_id] = room; ws.on('message', function(msg) { room.connections.forEach(function(conn) { conn.send(msg); }); }); next(); });