javascript - 使用带有 socket.io 的房间

标签 javascript node.js sockets websocket 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(...) 加入房间?

最佳答案

对于我制作的俳句共享应用程序,我有这样的东西:

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

关于javascript - 使用带有 socket.io 的房间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39377254/

相关文章:

node.js - Node,js - Mongoose - 无法保存地理多边形 - CastError : Cast to number failed

javascript - 在替换 ng-repeat 之前调用自定义指令链接函数

javascript - 如何设计商店(应用程序状态)以便我们直接更改商店中的数据而无需操作, reducer ?

javascript - 如何在 websocket javascript 客户端中传递授权承载访问 token

node.js - Electron import x509 cert to local keychain (macOS) - 授权被拒绝,因为无法进行用户交互

sockets - 具有自定义负载平衡的 ZMQ 套接字

javascript - Node.js 和 Browserify 的 ReferenceError

javascript - ldapjs 身份验证(用户登录设置)

c++ - NAT 上的 UDP 失败

linux - 从硬件本身查找原始 MAC 地址