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) {
socket.to(5).send('newChatMessage_response', { data: message});
});

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

Answers:

Answer

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 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)

Answer

It's hard to say exactly how to do this without seeing your full code, but it sounds like you want to call the emit method on the individual socket you're trying to send to. If this is different from the socket making the connection (ie., a private chat partner) then you'll need some other way of storing and retrieving the correct socket you're trying to communicate with.

var sck = someFunctionToGetAppropriateSocketObject();
sck.emit('newChatMessage_response', { data: message});

see http://socket.io/#how-to-use and https://github.com/learnboost/socket.io

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.