首页 > 解决方案 > 如何在 Strapi 服务器上设置套接字连接

问题描述

我正在尝试将 socket.io 与strapi 集成。但不幸的是,如果没有任何适当的教程或文档涵盖这方面,我就无法做到这一点。

我跟着我在网上找到的唯一资源是: https ://medium.com/strapi/strapi-socket-io-a9c856e915a6 但我认为这篇文章已经过时了。我似乎无法运行其中提到的代码而不会遇到大量错误。

下面是我实现它的尝试,我一直在尝试通过 chrome websocket 插件智能 websocket 客户端连接它但是当我尝试运行服务器时没有得到任何响应。

我完全处于黑暗之中。任何帮助将不胜感激

module.exports = ()=> {
  // import socket io
  var io = require('socket.io')(strapi.server)
  console.log(strapi.server) //undefined
  // listen for user connection
  io.on('connect', socket => {
  
      socket.send('Hello!');
      console.log("idit")

      // or with emit() and custom event names
      socket.emit('greetings', 'Hey!', { 'ms': 'jane' }, Buffer.from([4, 3, 3, 1]));

      // handle the event sent with socket.send()
      socket.on('message', (data) => {
        console.log(data);
      });

      // handle the event sent with socket.emit()
      socket.on('salutations', (elem1, elem2, elem3) => {
        console.log(elem1, elem2, elem3);
      });
    });
};

标签: socket.iostrapi

解决方案


所以我找到了解决方案。耶。我会把它放在这里以防万一有人需要它。

boostrap.js

module.exports = async () => {
  process.nextTick(() =>{
    var io = require('socket.io')(strapi.server);
    io.on('connection', async function(socket) {

      console.log(`a user connected`)
      // send message on user connection
      socket.emit('hello', JSON.stringify({message: await strapi.services.profile.update({"posted_by"})}));


      // listen for user diconnect
      socket.on('disconnect', () =>{
        console.log('a user disconnected')
      });
    });
    strapi.io = io; // register socket io inside strapi main object to use it globally anywhere
  })

};

在以下位置找到:https ://github.com/strapi/strapi/issues/5869#issuecomment-619508153 _

显然,socket.server 在服务器启动时不可用。因此,您必须使用等待 socket.server 初始化的 process.nextTick。

我还将添加一些我在设置时遇到的问题。

如何从 nuxt、vue 或 react 等外部客户端连接?

您只需通过“http://localhost:1337”进行连接,这是我通常使用的 Strapi 地址。

我正在使用 nuxt 作为我的客户端,这就是在客户端设置我的 socketio 的方式

  1. 我首先通过 npm 安装了 nuxt-socket-io
  2. 根据文档编辑了 nuxt.config 文件
modules:[
  ...
  'nuxt-socket-io',
  ...
],
io: {
    // module options
    sockets: [
      {
        name: 'main',
        url: 'http://localhost:1337',
      },
    ],
  },
  1. 然后我终于在我的一个页面中添加了一个监听器。
created() {
    this.socket = this.$nuxtSocket({})
    this.socket.on('hello', (msg, cb) => {
      console.log('SOCKET HI')
      console.log(msg)
    })
},

它有效。


推荐阅读