如何使用socket.io向特定客户端发送消息
我从socket.io + node.js开始,我知道如何在本地发送消息并广播 socket.broadcast.emit()
功能: - 所有连接的客户端收到相同的消息。
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.
现在,我想知道如何向特定客户端发送私人消息,我的意思是一个私人聊天的插槽2人之间(客户端到客户端流)。谢谢。
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.
当用户连接时,它应该使用必须唯一的用户名向服务器发送消息,例如一封电邮。
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 = {
'userA@example.com': [socket object],
'userB@example.com': [socket object],
'userC@example.com': [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)
在客户端上,侦听来自名为'receivedMessage'的服务器的发出,并通过阅读您可以处理它来自哪些数据以及发送的消息。
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.