如何在 strapi 服务器上建立套接字连接
How to set up a socket connection on a strapi server
我正在尝试将 socket.io 与 strapi 集成。但不幸的是,如果没有涵盖这方面的任何适当的教程或文档,我无法这样做。
我跟着我在网上找到的唯一资源是:
https://medium.com/strapi/strapi-socket-io-a9c856e915a6
但我认为这篇文章已经过时了。我似乎 运行 里面提到的代码没有 运行 成吨的错误。
下面是我尝试实现它的尝试,我一直在尝试通过 chrome websocket 插件 smart websocket client 连接它但是我没有收到任何响应我尝试 运行 服务器。
我完全一头雾水。任何帮助将不胜感激
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);
});
});
};
所以我找到了解决方案。耶。我会把它放在这里以防万一有人需要它。
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 的方法
- 我首先通过 npm 安装了 nuxt-socket-io
- 根据文档编辑了 nuxt.config 文件
modules:[
...
'nuxt-socket-io',
...
],
io: {
// module options
sockets: [
{
name: 'main',
url: 'http://localhost:1337',
},
],
},
- 然后我终于在我的一个页面中添加了一个监听器。
created() {
this.socket = this.$nuxtSocket({})
this.socket.on('hello', (msg, cb) => {
console.log('SOCKET HI')
console.log(msg)
})
},
而且有效。
将第三方服务集成到 Strapi 中的一种简洁方法是使用 hooks. They are loaded once during the server boot. In this case, we will create a local hook。
以下示例适用于 strapi@3.6
。
- 在
./hooks/socket.io/index.js
为 socket.io
创建一个挂钩
module.exports = strapi => {
return {
async initialize() {
const ioServer = require('socket.io')(strapi.server, {
cors: {
origin: process.env['FRONT_APP_URL'],
methods: ['GET', 'POST'],
/* ...other cors options */
}
})
ioServer.on('connection', function(socket) {
socket.emit('hello', `Welcome ${socket.id}`)
})
/* HANDLE CLIENT SOCKET LOGIC HERE */
// store the server.io instance to global var to use elsewhere
strapi.services.ioServer = ioServer
},
}
}
- 启用新挂钩以便 Strapi 加载它 -
./config/hook.js
module.exports = {
settings: {
'socket.io': {
enabled: true,
},
},
};
大功告成。您可以在 ./config/functions/bootstrap.js
或 models' lifecycle hooks.
中访问 websocket 服务器
// ./api/employee/models/employee.js
module.exports = {
lifecycles: {
async afterUpdate(result, params, data) {
strapi.services.ioServer.emit('update:employee', result)
},
},
};
致那些正在使用 Strapi 版本 4 寻找答案的人
var io = require("socket.io")(strapi.server.httpServer)
我正在尝试将 socket.io 与 strapi 集成。但不幸的是,如果没有涵盖这方面的任何适当的教程或文档,我无法这样做。
我跟着我在网上找到的唯一资源是: https://medium.com/strapi/strapi-socket-io-a9c856e915a6 但我认为这篇文章已经过时了。我似乎 运行 里面提到的代码没有 运行 成吨的错误。
下面是我尝试实现它的尝试,我一直在尝试通过 chrome websocket 插件 smart websocket client 连接它但是我没有收到任何响应我尝试 运行 服务器。
我完全一头雾水。任何帮助将不胜感激
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);
});
});
};
所以我找到了解决方案。耶。我会把它放在这里以防万一有人需要它。
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 的方法
- 我首先通过 npm 安装了 nuxt-socket-io
- 根据文档编辑了 nuxt.config 文件
modules:[
...
'nuxt-socket-io',
...
],
io: {
// module options
sockets: [
{
name: 'main',
url: 'http://localhost:1337',
},
],
},
- 然后我终于在我的一个页面中添加了一个监听器。
created() {
this.socket = this.$nuxtSocket({})
this.socket.on('hello', (msg, cb) => {
console.log('SOCKET HI')
console.log(msg)
})
},
而且有效。
将第三方服务集成到 Strapi 中的一种简洁方法是使用 hooks. They are loaded once during the server boot. In this case, we will create a local hook。
以下示例适用于 strapi@3.6
。
- 在
./hooks/socket.io/index.js
为
socket.io
创建一个挂钩
module.exports = strapi => {
return {
async initialize() {
const ioServer = require('socket.io')(strapi.server, {
cors: {
origin: process.env['FRONT_APP_URL'],
methods: ['GET', 'POST'],
/* ...other cors options */
}
})
ioServer.on('connection', function(socket) {
socket.emit('hello', `Welcome ${socket.id}`)
})
/* HANDLE CLIENT SOCKET LOGIC HERE */
// store the server.io instance to global var to use elsewhere
strapi.services.ioServer = ioServer
},
}
}
- 启用新挂钩以便 Strapi 加载它 -
./config/hook.js
module.exports = {
settings: {
'socket.io': {
enabled: true,
},
},
};
大功告成。您可以在 ./config/functions/bootstrap.js
或 models' lifecycle hooks.
// ./api/employee/models/employee.js
module.exports = {
lifecycles: {
async afterUpdate(result, params, data) {
strapi.services.ioServer.emit('update:employee', result)
},
},
};
致那些正在使用 Strapi 版本 4 寻找答案的人
var io = require("socket.io")(strapi.server.httpServer)