【问题标题】:Socket.io - Socket splitting into rooms [closed]Socket.io - 套接字拆分成房间 [关闭]
【发布时间】:2017-08-24 17:53:15
【问题描述】:

我正在尝试创建一个多人游戏,为每个连接的 两个 套接字创建新房间。我该怎么做呢?有人可以举个例子吗?

【问题讨论】:

标签: javascript node.js socket.io


【解决方案1】:

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

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)

此示例的问题在于,如果房间中的一名玩家离开游戏,另一名玩家将独自一人,直到他或她刷新页面。根据应用程序,您可能需要在此处添加一些逻辑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-09
    • 2013-10-03
    • 2020-03-17
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    • 2015-08-05
    相关资源
    最近更新 更多