Reputation: 11782
I am using socket.io and node.js/mongoDB for an app which will send real time analytics between Parents
and Drivers
Let's say Driver is moving along a path and for every location change he will send his location to a list of specific parents.
I can think of one approach to achieve such functionality
1- I create two arrays
var userSockets = {};
var driverSockets = {};
Whenever a user/driver is connected i do
For Driver - driverSockets[accId] = socket
For User - userSockets[accId] = socket
Now if a driver has to emit a location change, he will do something like
userSockets[userId].emit(abc)
I would like to know if this approach is better? Would it be better to save users as onlineUsers in MongoDB but even then how to access their sockets to emit data.
What would be the best approach.
Upvotes: 2
Views: 887
Reputation: 755
You should use "room" to store online user and emit to this room(channel) when location change.
//join a room(channel)
socket.join('online');
//sending to sender client, only if they are in 'online' room(channel)
socket.to('online').emit('location', {user_type:'driver'});
Upvotes: 1
Reputation: 457
Here is the example code to seperate driver and parents in different array with user_type key-word and send driver location to all the parents in real time. Furthermore, We can add users mobile number to send specific driver location to a specific parent etc.
var parents = [];
var drivers = [];
var users = [];
io.on('connection', function(socket){
users.push(socket);
socket.on('disconnect', function(msg){
var i = users.indexOf(socket);
users.splice(i, 1);
var j = parents.indexOf(socket);
if(j !== -1){
parents.splice(j, 1);
}
var k = drivers.indexOf(socket);
if(k !== -1){
drivers.splice(k, 1);
}
});
socket.on('register', function(msg){
console.log(msg);//send json- {"user_type":"driver"}
var data = JSON.parse(msg);
var i = users.indexOf(socket);
if(data.user_type === 'driver'){
drivers.push(users[i]);
}else{
parents.push(users[i]);
}
users[i].emit('register', '{"status":"registered"}');
});
socket.on('location', function(msg){
console.log(msg);//send json- {"user_type":"driver","location":"lat,long"}
var data = JSON.parse(msg);
if(data.user_type === 'driver'){
for(var x=0;x<parents.length;x++){
parents[x].emit('location', '{"user_type":"driver", "location":"lat,long"}');
}
}
});
});
Upvotes: 0