首页 > 解决方案 > 关于套接字 io 库的“命名空间”功能的混淆

问题描述

套接字 io noob 在这里。

我用socket io工作了一个月。我想构建一个实时应用程序并选择“不和谐”作为示例。我在不和谐中看到他们有“服务器”,并且在每个“服务器”下,您可以创建多个可以聊天的频道。

从 socket io docs 中,我发现我可以创建命名空间,这些命名空间基本上是同一底层连接下的套接字池。

而 socket io 中的“ rooms ”充当节点,您可以将套接字插入服务器端定义的此类节点。

我的问题是,不和谐的“服务器”是否与套接字 io 库中的“命名空间”一样?我知道不和谐频道就像房间

我尝试根据这个想法编写几行代码。我在前端制作了一个“ create-namespacerequest.boy ”表单,在提交时,使用 ajax 发送了一个发布请求,其中包含命名空间的名称。在服务器端,我解析它以创建一个命名空间。在这里,我展示了我写的一些意大利面。

我的客户端代码如下所示。稍后我将解释我在这里所做的事情:


/* Part of Client side code */

const nsp_dialog = document.getElementById('nsp-dialog') // The form
const nsp_list = document.getElementById('nsp-list')

nsp_dialog.addEventListener('close', async e => { // The form to create a "namespace" is a "dialog"
                                                  // form, so it responds to "close" event (somewhat 
                                                  // equivalent to "submit" event)    
                             
  const nsp = nsp_input.value // parse input value on the form 

  nsp_list.innerHTML += create_nsp(nsp) // Append to the list to show on UI

  const res = await fetch('', { // Send ajax request to the backend, with the name
    method: 'POST',             // of the "namespace" just created
    body: JSON.stringify({ nsp }),
    headers: { 'Content-Type': 'application/json' }
  })

  const data = await res.json()

  if (data.msg === 'successful') { // Backend sends confirmation that nsp has been created

    const new_socket = io(`/${nsp}`) // Apply for a socket
    new_socket.on('connect', () => {
      console.log(new_socket.id)
    })
    new_socket.emit('nsp-event', `got ${nsp} event`) // Fire an event upon that socket
  }
})

function create_nsp (nsp) {
  return `
  <div class="each-nsp" id="${nsp}">
    ${nsp}
  </div>`
}

部分后端代码如下所示:

/* Part of Server side code */

let nsps_arr = [] // An array to hold the the name of nsps

app.post('/', (req, res) => {

  let new_nsp = '/' + req.body.nsp // req.body holds nsp name, like "myServer", and '/'
                                   // is added to make a valid nsp name like "/myServer"
  nsps_arr.push({
    name: new_nsp 
  })

  let this_nsp = io.of(`${new_nsp}`) // define a new nsp with the name parsed from req.body

  this_nsp.on('connection', socket => { // Connect with the new namespace. And wait for client 
                                        // side code to apply for a socket for this nsp. It should
                                        // fire an event towards us.
    console.log('new socket:', socket.id)

    socket.on('nsp-event', msg => { // After client side code made the socket for this namespace
                                    // it fired this event and it is successfully caught here.
      console.log('event triggered:', msg)
    })
  })

  res.status(201).json({ msg: 'successful' })

})

总结是:

客户端有一个表单来创建“服务器”或“命名空间”。当用户点击提交时,会在 UI 上附加一个“服务器”名称,同时服务器名称也被发送到后端以创建一个实际的命名空间。

当在后端创建 nsp 时,它会发送一个状态(201),当客户端接收到信号时,它会向该命名空间申请一个套接字并尝试在该套接字上触发一个事件。

服务器接收到事件,并将确认消息记录到控制台。

这就是我到目前为止所做的一切。我想问,不和谐的“服务器”可以与套接字 io“命名空间”相提并论吗?

而我开始的方式,这种方法可以吗?

我需要一些想法来了解如何进一步推动这个项目。

非常感谢您阅读我的求助。:) 希望你拥有美好的一天。

标签: javascriptnode.jssocket.io

解决方案


推荐阅读