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.

现在,我想知道如何向特定的客户端发送私有消息,我的意思是两个人之间的私有聊天使用一个套接字(客户端到客户端流).谢谢.

推荐答案

当用户连接时,它应该向服务器发送一条用户名必须唯一的消息,比如邮箱.

一对用户名和套接字应存储在如下对象中:

var users = {
    'userA@example.com': [socket object],
    'userB@example.com': [socket object],
    'userC@example.com': [socket object]
}

在客户端上,向服务器发送包含以下数据的对象:

{
    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"的服务器发出的信息,通过读取数据,您可以处理这些信息来自谁以及发送的消息.

Jquery相关问答推荐

当父迪瓦是重复元素时,如何将一些子元素包裹在父迪瓦中

如何在光滑的轮播上添加进度条

从 React 到 Node 服务器的 ajax 调用中的数据未定义

Jquery如何通过数组中的属性查找对象

提高 jQuery Select 器性能的好方法?

如何在 jquery 中包含 !important

在页面上放置文件时如何设置文件输入值?

jQuery 绑定点击 *ANYTHING* 但 *ELEMENT*

如何使用 jQuery 显示忙碌指示器?

blueimp 文件上传插件中的 maxFileSize 和 acceptFileTypes 不起作用.为什么?

在javascript中检测按键的最简单方法

使用 jQuery 获取选定的选项 id

复选框值始终为打开

Jquery Ajax 错误处理忽略中止

如何在 JavaScript 中的对象数组中查找值?

jQuery 追加淡入

查找 id 以开头的 html 元素

如何使用 jQuery 检测 IE 8?

使用 jQuery 和 CSS 将数字转换为星级显示

如何使用 jquery 更改元素类型