首页 > 解决方案 > 如何使用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

标签: node.jssocket.io

解决方案


要将消息发送到特定房间,您必须使用 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');

您可以关注这个问题以获取有关如何创建房间的详细信息?

在 Socket.io 中创建房间

emit备忘单也可能有用: https ://github.com/socketio/socket.io/blob/master/docs/emit.md


推荐阅读