Socket.IO subscribe to multiple channels

2019-01-20 23:11发布

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.

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. 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?

  2. A user can join multiple rooms simultaneously.

  3. 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
1条回答
Rolldiameter
2楼-- · 2019-01-20 23:49

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.

Server

io.sockets.on('connection', function(socket){
    socket.on('subscribe', function(room) { 
        console.log('joining room', room);
        socket.join(room); 
    })

    socket.on('unsubscribe', function(room) {  
        console.log('leaving room', room);
        socket.leave(room); 
    })

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

Client

 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 });
 });

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');
});
查看更多
登录 后发表回答