I'm making a simple chatroom in meteor. How would I get a list of currently active users? Is there a way to actually get a list of current connections / clients?
I browsed the meteor sources yesterday to see if there is already anything like that. I couldn't find a connected flag or anything...
I think you'll have two options:
Implement a heartbeat in the client and the server for every connected user. I personally don't like this idea very much, as this could result in zillions of intervals running on your server.
Use the sockjs server to get the open sockets. Meteor.default_server.stream_server.all_sockets()
returns an array with all opened sockets. You could than have a single interval looking for changes in that (or better you'll listen to changes of the sockjs server itself, there is a register
method that could be useful), map the open sockets with your users and use a collection to push it to your clients.
Each client knows his socket id, so the mapping shouldnt be to hard.
I didn't implement it yet, so these are only ideas where to start.
I created a REST endpoint to expose the number of current active users...
/server/main.js
import bodyParser from 'body-parser'
import { Picker } from 'meteor/meteorhacks:picker'
Picker.middleware(bodyParser.json())
Picker.route('/api/status', ({ provider }, request, response) => {
response.statusCode = 200
response.end(JSON.stringify({
active_users: Meteor.default_server.stream_server.all_sockets().length
}))
})
Output
{"active_users":1}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With