I want to send data to the specified user, and no one else.
currently to broadcast to everyone I do:
socket.on('newChatMessage', function (message) {
socket.broadcast.emit('newChatMessage_response', { data: message});
});
now what I want to do is simply something like:
socket.on('newChatMessage', function (message) {
socket.to(5).send('newChatMessage_response', { data: message});
});
to(5) would be the user with the ID of 5.
I think the missing piece for you is inside this function:
io.sockets.on('connection', function(socket) { ... });– That function executes every time there is a connection event. And every time that event fires, the ‘socket’ argument references a brand new socket object, representing the newly connected user. You then need to store that socket object somewhere in a way that you can look it up later, to call either the send or emit method on it, if you need to send messages that will be seen by only that socket.Here’s a quick example that should get you started. (Note: I haven’t tested this, nor do I recommend that it’s the best way to do what you’re trying to do. I just wrote it up in the answer editor to give you an idea of how you could do what you’re looking to do)
Edit: If by id you’re referring to the id value that socket.io assigns, not a value that you’ve assigned, you can get a socket with a specific id value using
var socket = io.sockets.sockets['1981672396123987'];(above syntax tested using socket.io v0.7.9)