socket.io private message


Question

I've beeen scouring the Net with no luck. I'm trying to figure out how to send a private message from one user to another. There are lots of snippets, but I'm not sure about the client/server interaction. If I have the ID of the socket I want to send to, how do I send it to the server, and how do I ensure the server only sends the message to that one receiver socket?

Is there a tutorial or walkthrough that anyone knows of?

1
20
7/6/2012 4:48:03 AM

Accepted Answer

No tutorial needed. The Socket.IO FAQ is pretty straightforward on this one:

socket.emit('news', { hello: 'world' });

EDIT: Folks are linking to this question when asking about how to get that socket object later. There is no need to. When a new client connects, save a reference to that socket on whatever object you're keeping your user information on. My comment from below:

In the top of your script somewhere, setup an object to hold your users' information.

var connectedUsers = {};

In your .on('connection') function, add that socket to your new object. connectedUsers[USER_NAME_HERE] = socket; Then you can easily retrieve it later. connectedUsers[USER_NAME_HERE].emit('something', 'something');

30
9/18/2014 8:27:18 PM

Here's a code snippet that should help:

Client-side (sending message)

socket.emit("private", { msg: chatMsg.val(), to: selected.text() });

where to refers to the id to send a private message to and msg is the content.

Client-side (receiving message)

socket.on("private", function(data) {   
   chatLog.append('<li class="private"><em><strong>'+ data.from +' -> '+ data.to +'</strong>: '+ data.msg +'</em></li>');
});

where chatLog is a div displaying the chat messages.

Server-side

client.on("private", function(data) {       
    io.sockets.sockets[data.to].emit("private", { from: client.id, to: data.to, msg: data.msg });
    client.emit("private", { from: client.id, to: data.to, msg: data.msg });
});

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon