使用socket.io管理多个聊天室的正确方法是什么? [英] What is the proper way to manage multiple chat rooms with socket.io?

查看:160
本文介绍了使用socket.io管理多个聊天室的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用socket.io管理多个聊天室的正确方法是什么?

What is the proper way to manage multiple chat rooms with socket.io?

因此,在服务器上将出现以下内容:

So on the server there would be something like:

io.sockets.on('connection', function (socket) {
  socket.on('message', function (data) {
    socket.broadcast.emit('receive', data);
  });
});

现在,这对于一个房间来说可以正常工作,因为它会将消息广播给所有连接的人。您如何向位于特定聊天室中的人发送消息?

Now this would work fine for one room, as it broadcasts the message out to all who are connected. How do you send messages to people who are in specific chat rooms though?

添加.of(’/ chat / room_name’)吗?
还是将每个人的数组存储在一个房间中?

Add .of('/chat/room_name')? Or store an array of everybody in a room?

推荐答案

Socket.IO v0.7现在为您提供了一个 Socket 每个定义的命名空间:

Socket.IO v0.7 now gives you one Socket per namespace you define:

var room1 = io.connect('/room1');
room1.on('message', function () {
    // chat socket messages
});
room1.on('disconnect', function () {
    // chat disconnect event
});

var room2 = io.connect('/room2');
room2.on('message', function () {
    // chat socket messages
});
room2.on('disconnect', function () {
    // chat disconnect event
});

使用不同的套接字,可以有选择地发送到您想要的特定命名空间。

With different sockets, you can selectively send to the specific namespace you would like.

Socket.IO v0.7也具有房间的概念

Socket.IO v0.7 also has concept of "room"

io.sockets.on('connection', function (socket) {
  socket.join('a room');
  socket.broadcast.to('a room').send('im here');
  io.sockets.in('some other room').emit('hi');
});

来源: http://socket.io/#announcement

这篇关于使用socket.io管理多个聊天室的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆