Katcha Katcha - 2 years ago 166
Javascript Question

How to send a message to a particular client with socket.io

I'm starting with socket.io + node.js, I know how to send a message locally and to broadcast

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download