Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 416
Dylan Cross Avatar asked Feb 04 '12 02:02

Dylan Cross


People also ask

Is Socket.IO better than WebSocket?

Socket.IO is way more than just a layer above WebSockets, it has different semantics (marks messages with name), and does failovers to different protocols, as well has heartbeating mechanism. More to that attaches ID's to clients on server side, and more. So it is not just a wrapper, it is full-featured library.

How do I send a message to a socket?

The send() function initiates transmission of a message from the specified socket to its peer. The send() function sends a message only when the socket is connected (including when the peer of the connectionless socket has been set via connect()). The length of the message to be sent is specified by the len argument.


1 Answers

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)

like image 119
fourk Avatar answered Sep 28 '22 00:09

fourk