I'm starting with socket.io + node.js, I know how to send a message locally and to broadcast socket.broadcast.emit()
function:- all the connected clients receive the same message.
Now, I would like to know how to send a private message to a particular client, I mean one socket for a private chat between 2 person (Client-To-Client stream). Thanks.
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.
So as we all know Socket.io is the best solution for instant messaging app and its reliability.
You can use socket.io rooms. From the client side emit an event ("join" in this case, can be anything) with any unique identifier (email, id).
Client Side:
var socket = io.connect('http://localhost'); socket.emit('join', {email: [email protected]});
Now, from the server side use that information to create an unique room for that user
Server Side:
var io = require('socket.io').listen(80); io.sockets.on('connection', function (socket) { socket.on('join', function (data) { socket.join(data.email); // We are using room of socket io }); });
So, now every user has joined a room named after user's email. So if you want to send a specific user a message you just have to
Server Side:
io.sockets.in('[email protected]').emit('new_msg', {msg: 'hello'});
The last thing left to do on the client side is listen to the "new_msg" event.
Client Side:
socket.on("new_msg", function(data) { alert(data.msg); }
I hope you get the idea.
When a user connects, it should send a message to the server with a username which has to be unique, like an email.
A pair of username and socket should be stored in an object like this:
var users = { '[email protected]': [socket object], '[email protected]': [socket object], '[email protected]': [socket object] }
On the client, emit an object to the server with the following data:
{ to:[the other receiver's username as a string], from:[the person who sent the message as string], message:[the message to be sent as string] }
On the server, listen for messages. When a message is received, emit the data to the receiver.
users[data.to].emit('receivedMessage', data)
On the client, listen for emits from the server called 'receivedMessage', and by reading the data you can handle who it came from and the message that was sent.
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