关于javascript:Socket.io-套接字拆分为多个房间

Socket.io - Socket splitting into rooms

我正在尝试创建一个多人游戏,为每个连接的两个插槽创建新的房间。我将如何去做呢?有人可以举个例子吗?


您可以使用以下示例作为起点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
const io = require('socket.io')()

/* room to join next connected socket */
let prevRoom = null

io.on('connection', socket => {
  let room

  if (prevRoom == null) {
    /* create new room if there is no room with one player */
    room = Math.random().toString(36).slice(2)
    prevRoom = room
  } else {
    /* join existing room with one player and mark that it is now complete */
    room = prevRoom
    prevRoom = null
  }

  socket.join(room)

  /* send message from one socket in this room to another */
  socket.on('message', data => {
    socket.broadcast.to(room).emit('message', data)
  })
})

io.listen(3000)

此示例的问题是,如果房间中的一位玩家离开游戏,那么另一个人将保持孤独,直到他或她刷新页面为止。根据应用程序的不同,您可能需要在此处添加一些逻辑。