繁体   English   中英

使用带socket.io的房间

[英]Using rooms with socket.io

socket.io文档中,我看到了一个房间的例子

io.on('connection', function(socket){
  socket.on('say to someone', function(id, msg){
    socket.broadcast.to(id).emit('my message', msg);
  });
});

我有一条路线/rooms/:roomId

是否可以使服务器和客户端之间发送的套接字只能到达特定的房间?

我想服务器应该是这样的

io.on('connection', function(socket){
  socket.on('new msg from client', function(roomId, msg){
    io.to(id).emit('new msg from server', msg);
  });
});

上面和客户端应该发送消息

socket.emit('new msg from client', roomId, msg);

只需使用即可获得新消息

socket.on('new msg from server', function () {
  document.getElementById('msgs').appendChild(...);
});

但这会有效吗? 在我能做到这一点之前,我不应该和socket.join(...)一起加入房间吗?

对于haiku共享应用程序,我做了类似这样的事情:

io.on('connection', function(socket) {
    var socket_id = socket.id;
    var client_ip = socket.handshake.headers['x-forwarded-for'] || socket.handshake.address.address;
    clients.push(socket);
    console.info('New client connected (id=' + socket.id + ').');

    number_of_clients_connected++;
    console.log('[' + client_ip + '] connected, ' + number_of_clients_connected + ' total users online.');

    //when a socket is disconnected or closed, .on('disconnect') is fired
    socket.on('disconnect', function() {
        number_of_clients_connected--;
        console.log('[' + client_ip + '] disconnected, ' + number_of_clients_connected + ' total users online.');
        //on disconnect, remove from clients array
        var index = clients.indexOf(socket);
        if (index != -1) {
            clients.splice(index, 1);
            //console.info('Client gone (id=' + socket.id + ').');
        }
    });

因此它保留了一组客户端,当某些消息需要中继时,您可以指定客户端套接字ID ...

//reads from latest_haikus_cache and sends them
socket.on('request_haiku_cache', function() {
    latest_haikus_cache.forEach(function(a_latest_haiku) {
        clients[clients.indexOf(socket)].emit('load_haiku_from_cache', a_latest_haiku);
    });
});

允许服务器向任何房间广播,这样您就可以支持让客户端要求服务器发送到没有该客户端在房间内的房间。 这真的取决于你想做什么。

因此,如果您希望您的服务器拥有此代码,允许任何客户端向他们选择的任何房间发送消息:

io.on('connection', function(socket){
  socket.on('new msg from client', function(roomId, msg){
    io.to(roomId).emit('new msg from server', msg);
  });
});

然后,你确实可以这样做,它会起作用。 它是否合适完全取决于您的应用程序,以及您是否希望任何客户能够广播到任何名称为的房间。

但这会有效吗?

是的,它会起作用。

在我能做到这一点之前,我不应该和socket.join(...)一起加入房间吗?

除非客户希望接收该房间的消息,否则无需让客户加入房间。 如果您想要这样做,您没有在房间里要求服务器发送到该房间。 所以,这完全取决于您的应用程序和适当的选择。

我有一条路线/ rooms /:roomId。

是否可以使服务器和客户端之间发送的套接字只能到达特定的房间?

我无法弄清楚你问题的这一部分意味着什么。 如果您想进一步解释,我也会尝试帮助解决这个问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM