node.js - 如何使用nodejs socket.io向特定房间的用户发送打字警报和消息
问题描述
下面的代码通过向所有连接的用户广播输入通知和聊天消息来正常工作。
这就是我想要的:如何仅向连接到特定房间的用户发送打字通知和聊天消息,例如 Room1、Room2 等。
这是代码
索引.html
var socket = io();
var user = 'nancy';
function submitfunction(){
var from = 'nancy';
var message = 'hello Nancy';
socket.emit('chatMessage', from, message);
}
function notifyTyping() {
var user = 'nancy'
socket.emit('notifyUser', user);
}
socket.on('chatMessage', function(from, msg){
//sent message goes here
});
socket.on('notifyUser', function(user){
$('#notifyUser').text(nancy is typing ...');
setTimeout(function(){ $('#notifyUser').text(''); }, 10000);
});
服务器.js
var io = require('socket.io')(http);
io.on('connection', function(socket){
socket.on('chatMessage', function(from, msg){
io.emit('chatMessage', from, msg);
});
socket.on('notifyUser', function(user){
io.emit('notifyUser', user);
});
});
我正在使用 npm 安装的 socket.io ^2.3.0
解决方案
要将消息发送到特定房间,您必须使用 roomId 创建并加入房间。下面是一个基本的代码片段
//client side
const socket = io.connect();
socket.emit('create', 'room1');
// server side code
socket.on('create', function(room1) {
socket.join(room1);
});
To emit data to a specific room
// sending to all clients in 'room1'except sender
socket.to('room1').emit('event',data);
// sending to all clients in 'room1' room, including sender
io.in('room1').emit('event', 'data');
您可以关注这个问题以获取有关如何创建房间的详细信息?
此emit
备忘单也可能有用:
https ://github.com/socketio/socket.io/blob/master/docs/emit.md
推荐阅读
- functional-programming - 跨越可重复键
- c++ - 在 C++ 中解析输入以进行竞争性编程
- reactjs - 当获得一个许可证密钥时,停止视频播放器渲染。反应
- gitlab - 用于语法问题的 Lint GitLab 管道模板
- javascript - 基于复选框动态显示和隐藏 Div 的 Javascript 函数
- javascript - 如何检测我是作为 Node.js 脚本还是作为 JScript 脚本运行 .js 文件?
- recursion - DAX - 如何递归计算每日库存,考虑前一天的库存和今天的收据/预测?
- pyspark - 如何在 PySpark SQL when() 子句中使用聚合值?
- r - 即使缺少数据点,如何显示具有特定顺序(月年)的宽表?
- vue.js - nuxt-i18n:日期本地化对我不起作用