I use node.js and socket.io.
I have in my mysql table this data structure:
TABLE USERS:
Id: 1, Name: 'ABC1', ToUserId: 1
Id: 2, Name: 'ABC2', ToUserId: 1
Id: 3, Name: 'ABC3', ToUserId: 1
Id: 4, Name: 'ABC4', ToUserId: 2
Id: 5, Name: 'ABC5', ToUserId: 2
Id: 6, Name: 'ABC6', ToUserId: 2
Id: 7, Name: 'ABC7', ToUserId: 3
I want to send the rows (ID1 - ID3) as a collection to user with UserId 1 and the rows (ID4 - ID6) to user with UserId 2 and the row (ID7) to user with UserId 3.
How can i create the collection and send the collection to the user?
I read the data as follows:
getUsers: function(callback)
{
client.query(
'SELECT * FROM users',
function select(err, results, fields) {
if (err) {
throw err;
}
var userslist = {};
if (results.length > 0) {
for (var i = 0; i < results.length; i++) {
var row = results[i];
//Create colletion in object userslist
//Emit to specific user ------v
//io.sockets.socket(USER_ID).emit('sendusers', userslist )
}
}
else
{
userslist = {};
}
callback(userslist);
}
);
}
You will need to store the association between the socket id and the user id.
On your client you will need to emit the USER_ID of the current user.
Something like
socket= io.connect();
socket.on('connect', function(data){
socket.emit('init', user_id);
});
And on your server will need to set the user_id. You can do something like
io.sockets.on('connection', function(socket) {
socket.on('init', function(data) {
socket.set('user_id', data, function(){
console.log('user_id', data);
});
});
});
Then in your controller you can retrieve all the sockets and loop through them.
//to get all connections
var sockets = io.sockets.clients();
//to get the user_id associated with the socket
socket.get('user_id', function(err, user_id){
//do whatever you want!
//ex: if(user_id == ...){ socket.emit('channel', 'value'); }
});
Hope that helps!