如何使用 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.