Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

socket.io private message

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?

like image 245
Trevor Newhook Avatar asked Jul 06 '12 04:07

Trevor Newhook


People also ask

Is socket.io good for chat?

So as we all know Socket.io is the best solution for instant messaging app and its reliability.

How do I send a message to socket ID?

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.

How many messages can socket.io handle?

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.


2 Answers

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

like image 196
Brad Avatar answered Sep 22 '22 13:09

Brad


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 }); }); 
like image 25
almypal Avatar answered Sep 21 '22 13:09

almypal