Socket.IO 订阅多个频道 [英] Socket.IO subscribe to multiple channels

查看:43
本文介绍了Socket.IO 订阅多个频道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Socket.IO 之上构建一个简单的聊天室系统,用户可以在其中创建一个新的聊天室,然后人们可以开始聊天.

I want to build a simple chat room system on top of Socket.IO where user can create a new chat room and then people can start chatting.

这听起来很简单,但作为我现在正在运行的 Socket.IO 0.9.4,在阅读了一些 SO 帖子以及 socket.io 上的文档后,我越来越困惑.所以,我希望有人可以为我提供使用 0.9.4 的说明:

This sound simple but as the Socket.IO 0.9.4 I'm running now, after reading a few SO posts together with the document on socket.io, i'm getting more and more confused. So, I hope that someone can provide me with instruction that WORK with 0.9.4:

  1. 我需要一种订阅房间的方法.房间名称由用户选择.当消息发布在房间中时,用户应该会收到它.服务端代码应该怎么写,客户端代码应该怎么写?

  1. I need a way to subscribe to a room. The room name is chosen by user. When a message is posted in a room, the user should receive it. How should I write the server code, how should I write the client code?

一个用户可以同时加入多个房间.

A user can join multiple rooms simultaneously.

我想要另一个系统向某个房间的所有用户发送消息.这个另一个系统"通过由 express 处理的请求发送消息.我将如何编写该请求处理程序?

I want another system to send a message to all user in a certain room. This 'another system' send the message through a request handled by express. How would I write that request handler?

推荐答案

socket.io 房间功能非常简单.查看 LearnBoost wiki 上的文档.

This is all pretty straightforward with the socket.io rooms feature. Take a look at the documentation on LearnBoost wiki.

https://github.com/LearnBoost/socket.io/wiki/Rooms

它允许通过一个插座连接到多个房间.我使用以下代码进行了快速测试.

It allows for being connected to multiple rooms over a single socket. I put together a quick test with the following code.

服务器

io.sockets.on('connection', function(client){
    client.on('subscribe', function(room) { 
        console.log('joining room', room);
        client.join(room); 
    })
    
    client.on('unsubscribe', function(room) {  
        console.log('leaving room', room);
        client.leave(room); 
    })

    client.on('send', function(data) {
        console.log('sending message');
        io.sockets.in(data.room).emit('message', data);
    });
});

客户

 var socket = io.connect();
 socket.on('message', function (data) {
  console.log(data);
 });
 
 socket.emit('subscribe', 'roomOne');
 socket.emit('subscribe', 'roomTwo');
 
 $('#send').click(function() {
  var room = $('#room').val(),
   message = $('#message').val();
   
  socket.emit('send', { room: room, message: message });
 });

从 Express 路由发送消息也非常简单.

Sending a message from an Express route is pretty simple as well.

app.post('/send/:room/', function(req, res) {
    var room = req.params.room
        message = req.body;

    io.sockets.in(room).emit('message', { room: room, message: message });

    res.end('message sent');
});

这篇关于Socket.IO 订阅多个频道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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