由于没有服务器,我应该在新的 nuxt.js 设置中的何处添加此 websocket 代码?

Pir*_*App 4 websocket vue.js nuxt.js ws

  • 我正在使用没有服务器文件夹的新版本 Nuxt
  • 在旧版本中,您有一个服务器文件夹和一个包含应用程序的 index.js
  • 我想用新版本的 NuxtJS 添加 websocket WS 库

该库需要您通过调用 http.createServer(app) 创建的服务器实例,这意味着正在运行的 Express 应用程序的实例。您现在将使用此服务器实例来侦听 index.js 文件中的 3000。还要创建一个 sessionHandler,您可以通过使用 express-session 库调用 session({}) 来获取它

const WebSocket = require('ws')
function websocket({ server, sessionHandler, logger }) {
  // https://github.com/websockets/ws/blob/master/examples/express-session-parse/index.js, if you pass a server instance here 'upgrade' handler will crash
  const wss = new WebSocket.Server({ noServer: true })
  function noop() {}
  function heartbeat() {
    this.isAlive = true
  }
  wss.on('connection', (ws, request, client) => {
    ws.isAlive = true
    ws.on('pong', heartbeat)
    ws.on('message', (msg) => {
      logger.info(`Received message ${msg} from user ${client}`)
      ws.send(true)
    })
  })
  server.on('upgrade', (request, socket, head) => {
    sessionHandler(request, {}, () => {
      logger.info(`${JSON.stringify(request.session)} WEBSOCKET SESSION PARSED`)
      wss.handleUpgrade(request, socket, head, (ws) => {
        wss.emit('connection', ws, request)
      })
    })
  })
  // TODO use a setTimeout here  instead of a setInterval
  setInterval(function ping() {
    // wss.clients => Set
    wss.clients.forEach(function each(ws) {
      if (ws.isAlive === false) return ws.terminate()
      ws.isAlive = false
      ws.ping(noop)
    })
  }, 30000)
  return wss
}
module.exports = websocket
Run Code Online (Sandbox Code Playgroud)
  • 有谁知道我如何在没有服务器文件夹的情况下在新的 Nuxt 设置上进行这项工作

Use*_* 28 10

您可以创建自定义模块并使用nuxt 挂钩在侦听事件上获取服务器实例。

创建modules/ws.js

const WebSocket = require('ws')
const wss = new WebSocket.Server({ noServer: true })

wss.on('connection', ws => {
  ws.on('message', message => {
    console.log('received: %s', message);
  })
  ws.send('Hello')
})

export default function () {
  this.nuxt.hook('listen', server => {
    server.on('upgrade', (request, socket, head) => {
      wss.handleUpgrade(request, socket, head, ws => {
        wss.emit('connection', ws);
      })
    })
  })
}
Run Code Online (Sandbox Code Playgroud)

并在nuxt.config.js以下位置注册模块:

export default {
  modules: [
    '~/modules/ws'
  ]
}
Run Code Online (Sandbox Code Playgroud)

在您的情况下,您可以创建一个模块目录而不是单个文件来存储多个相关文件。

创建 modules/ws/index.js

const websocket = require('./websocket') // this is your file

export default function () {
  this.nuxt.hook('listen', server => {
    websocket({
      server,
      sessionHandler (request, _, cb) { // example
        cb()
      },
      logger: console // example
    })
  })
}
Run Code Online (Sandbox Code Playgroud)

然后将您的文件复制到modules/ws/websocket.js. 您可以使用module.exportsCommonJS格式或将其更改为ES Module格式,Nuxt(Webpack)可以处理。

在您的代码中,我注意到ws.send(true)导致错误TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received type boolean (true),这基本上意味着您无法发送布尔值。