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?
So as we all know Socket.io is the best solution for instant messaging app and its reliability.
You can try the code below:io.to(socket.id). emit("event", data); whenever a user joined to the server, socket details will be generated including ID. This is the ID really helps to send a message to particular people.
On the first item, there is no coded limit to how many event handlers a socket.io server can handle. A socket derives from an EventEmitter and it uses the EventEmitter's listener capabilities to allow someone to listen for events.
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');
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 }); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With