因为它没有服务器,所以在新的 nuxt.js 设置中我在哪里添加这个 websocket 代码?

Where do I add this websocket code in the new nuxt.js setup since it does not have server?

库需要一个服务器实例,您可以通过调用 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

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

创建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);
      })
    })
  })
}

并在nuxt.config.js中注册模块:

export default {
  modules: [
    '~/modules/ws'
  ]
}

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

创建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
    })
  })
}

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

In your code I notice that ws.send(true) cause an error 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) which basically mean you cannot send boolean.