【问题标题】:Is it possible to use Socket.io with NuxtJs?是否可以将 Socket.io 与 NuxtJs 一起使用?
【发布时间】:2018-09-25 06:27:38
【问题描述】:

我想在我的 Nuxtjs 中使用 socket.io。有可能吗?

我尝试了this tutorial,但出现以下错误:

These dependencies were not found:

* fs in ./node_modules/socket.io/lib/index.js
* uws in ./node_modules/engine.io/lib/server.js

【问题讨论】:

  • 您使用哪个版本的 Node.js?那么你可以分享你的“package.json”文件中的deps列表吗?

标签: socket.io nuxt.js


【解决方案1】:

使用 Nuxt.js + Socket.io 的更好方法是遵循 core-team 的官方示例:https://github.com/nuxt/nuxt.js/tree/dev/examples/with-sockets

【讨论】:

  • 嗨,我希望我参加聚会还不算太晚,但我决定将这个示例模块化,使其更加“npm-friendly”并推送到 npm repo。我刚刚创作了nuxt-socket-io 思路是:只要npm install,在nuxt.config中配置socket,就可以使用了。
  • 感谢您的意见。 @RichS
【解决方案2】:

Nuxt + socket.io

为我工作:

  1. 将项目创建为 nodejs 应用程序(不是静态页面);
  2. 安装socket.io npm i socket.io;
  3. 将 serverMiddleware 部分添加到 nuxt.config.js:
export default {
  ...,
  serverMiddleware: [
    {path: '/ws', handler: '~/api/srv.js'},
  ],
}
  1. 创建中间件/app/srv.js:
const app = require('express')()
const socket = require('socket.io')
let server = null
let io = null

app.all('/init', (req, res) => {
  if (!server) {
    server = res.connection.server
    io = socket(server)

    io.on('connection', function (socket) {
      console.log('Made socket connection');

      socket.on('msg', msg => {
        console.log('Recived: ' + msg)

        setTimeout(() => {
          socket.emit('msg', `Response to: ${msg}`)
        }, 1000)
      })

      socket.on('disconnect', () => console.log('disconnected'))
    })
  }

  res.json({ msg: 'server is set' })
})

module.exports = app

Socket.io 需要不是在中间件中创建的服务器,这就是为什么从res.connection.server 向应用程序发出的最触发请求。

  1. 创建页面pages/index.vue:
<template>
  <div class="container">
    <input v-model="msg">
    <button @click="socket.emit('msg', msg)">send</button>
    <br/>
    <textarea v-model="resps"></textarea>
  </div>
</template>

<script>
export default {
  head: {
    script: [
      {src: 'https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.4/socket.io.js'},
    ],
  },
  data () {
    return {
      socket: null,
      msg: 'wwJd',
      resps: '',
    }
  },
  mounted () {
    this.$axios.$get('/ws/init')
      .then(resp => {
        this.socket = io()
        this.socket.on('msg', msg => this.resps += `${msg}\n`)
      })
  },
}
</script>
  1. 运行它npm run dev;
  2. 修改和享受 :-)

【讨论】:

    【解决方案3】:

    更新了 GitHub 上链接示例的答案

    我建议使用 nuxt-socket-io moduleset up 真的很容易,有nice documentation

    我构建了this litte demo example,我将列出我构建它的步骤(这甚至比 npm 包的Setup section 更彻底):

    1. 将 nuxt-socket-io 依赖添加到您的项目中:

      yarn add nuxt-socket-io # or npm install nuxt-socket-io

    2. (如果你已经有socket.io服务器可以跳过这部分)

      在您的nuxt.config.js 文件中添加以下行:serverMiddleware: [ "~/serverMiddleware/socket-io-server.js" ](请不要将 serverMiddleware 与中间件混淆,这是两个不同的东西)

      然后,创建文件./serverMiddleware/socket-io-server.js,您可以在其中实现您的socket.io 服务器

      // This file is executed once when the server is started
      
      // Setup a socket.io server on port 3001 that has CORS disabled
      // (do not set this to port 3000 as port 3000 is where
      // the nuxt dev server serves your nuxt application)
      const io = require("socket.io")(3001, {
        cors: {
          // No CORS at all
          origin: '*',
        }
      });
      
      var i = 0;
      // Broadcast "tick" event every second
      // Or do whatever you want with io ;)
      setInterval(() => {
        i++;
        io.emit("tick", i);
      }, 1000);
      
      // Since we are a serverMiddleware, we have to return a handler,
      // even if this it does nothing
      export default function (req, res, next) {
        next()
      }
      
    3. (如果你已经安装了 Vuex,你可以跳过这个)

      添加以下空的 Vuex 存储,即创建文件./store/index.js,因为模块需要设置 Vuex。

      export const state = () => ({})
      
    4. 将 nuxt-socket-io 添加到 nuxt.config.js 的模块部分,这将启用 socket-io 客户端:

      {
        modules: [
          'nuxt-socket-io',
        ],
        // socket.io configuration
        io: {
        // we could have multiple sockets that we identify with names
        // one of these sockets may have set "default" to true
          sockets: [{
            default: true, // make this the default socket
            name: 'main', // give it a name that we can later use to choose this socket in the .vue file
            url: 'http://localhost:3001' // URL wherever your socket IO server runs
          }]
        },
      }
      
    5. 在你的组件中使用它:

      {
        data() {
          return {
            latestTickId: 0,
          };
        },
        mounted() {
          const vm = this;
      
          // use "main" socket defined in nuxt.config.js
          vm.socket = this.$nuxtSocket({
            name: "main" // select "main" socket from nuxt.config.js - we could also skip this because "main" is the default socket
          });
      
          vm.socket.on("tick", (tickId) => {
            vm.latestTickId = tickId;
          });
        },
      }
      
    6. 使用npm run dev 运行它并享受你的滴答事件:)

    【讨论】:

    • 嗨@Markus 我试过了但没用,我可以错过 server.js 吗?请问你能设置所有步骤吗?谢谢
    • 点赞!你能分享一下你的服务器文件是什么样子的吗?
    • 你好@BKF。我的原始答案不包括任何服务器代码。我更新了答案以显示完整的客户端服务器端。
    • 你好@PirateApp。我无法再访问代码,但我利用周六的时间设置了以下演示项目并相应地更新了答案。希望这可以帮助! github.com/NeonMika/nuxt-socket-io-demo
    猜你喜欢
    • 2016-04-01
    • 2016-02-28
    • 2021-11-15
    • 1970-01-01
    • 2012-05-23
    • 2018-06-10
    • 1970-01-01
    • 2021-11-12
    • 2011-01-20
    相关资源
    最近更新 更多