在服务器端创建一个房间ID,并使用sockets.io将客户端连接到它

时间:2017-04-17 04:23:09

标签: node.js sockets

我想在服务器端创建一个随机房间ID,并在连接时将其发送到客户端,如下所示:

io.sockets.on('connection', function(socket){
    var roomID = Math.random().toString(36).substring(2, 13);  
    io.emit('message', roomID);
    socket.on('subscribe', function(room) { 
        socket.join(room); 
    })
});

然后,一旦客户端拥有服务器创建的房间ID,我想将客户端加入该房间。

 var socket = io.connect();
 var lobby;
 socket.on('message', function (data) {
    lobby=data;
 });

 socket.emit('subscribe', lobby);

问题是我无法从lobby函数中提取socket.on()变量。如果我理解正确的话,那是因为它在匿名函数中,这使得它异步。

这里有解决方案吗,或者我是否因为在客户端给它起了名字而加入了一个房间?

更新:根据第一个答案,我更新了我的代码。

服务器:

io.sockets.on('connection', function(socket){
var roomID = Math.random().toString(36).substring(2, 13);  
io.emit('message', roomID);
    socket.on('subscribe', function(room) { 
        console.log('joining room', room);
        socket.join(room); 
        console.log(io.nsps['/'].adapter.rooms);
 })
});

客户端:

var socket = io.connect();
socket.on('message', function (lobby) {
  $('#msg').val(lobby);
  socket.emit('subscribe', lobby);
});

输出(一个浏览器会话):

joining room bugs69q9znr
{ TO1D6tBPU1TebZIPAAAA: Room { sockets: { TO1D6tBPU1TebZIPAAAA: true }, length:
1 },
  bugs69q9znr: Room { sockets: { TO1D6tBPU1TebZIPAAAA: true }, length: 1 } }

输出(两个浏览器会话):

joining room c8p8gioeca0
{ TO1D6tBPU1TebZIPAAAA: Room { sockets: { TO1D6tBPU1TebZIPAAAA: true }, length:
1 },
  bugs69q9znr: Room { sockets: { TO1D6tBPU1TebZIPAAAA: true }, length: 1 },
  HDWyB6JXsB1rf3PdAAAB: Room { sockets: { HDWyB6JXsB1rf3PdAAAB: true }, length:
1 },
  c8p8gioeca0: Room { sockets: { TO1D6tBPU1TebZIPAAAA: true }, length: 1 } }
joining room c8p8gioeca0
{ TO1D6tBPU1TebZIPAAAA: Room { sockets: { TO1D6tBPU1TebZIPAAAA: true }, length:
1 },
  bugs69q9znr: Room { sockets: { TO1D6tBPU1TebZIPAAAA: true }, length: 1 },
  HDWyB6JXsB1rf3PdAAAB: Room { sockets: { HDWyB6JXsB1rf3PdAAAB: true }, length:
1 },
  c8p8gioeca0:
   Room {
     sockets: { TO1D6tBPU1TebZIPAAAA: true, HDWyB6JXsB1rf3PdAAAB: true },
     length: 2 } }

为什么要将两个插座连接到我的第二个房间?

1 个答案:

答案 0 :(得分:0)

在你知道要加入的大厅之前,不要加入房间。

 var socket = io.connect();
 socket.on('message', function (lobby) {
   socket.emit('subscribe', lobby);
 });

对此也要谨慎......取决于你如何处理服务器端的事情,任何客户端都可以连接到他们想要的任何大厅。