Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Socket IO send to specified user ID

Socket IO send to specified user ID


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) {'newChatMessage_response', { data: message});

to(5) would be the user with the ID of 5.

Problem courtesy of: Dylan Cross


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)

var allSockets = [];
io.sockets.on('connection', function(socket) {
  var userId = allSockets.push(socket);
  socket.on('newChatMessage', function(message) {
    socket.broadcast.emit('newChatMessage_response', {data: message});
  socket.on('privateChatMessage', function(message, toId) {
    allSockets[toId-1].emit('newPrivateMessage_response', {data: message});
  socket.broadcast.emit('newUserArrival', 'New user arrived with id of: ' + userId);

Edit: If by id you're referring to the id value that 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 v0.7.9)

Solution courtesy of: fourk


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Socket IO send to specified user ID


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription