socketio封装

This commit is contained in:
robin
2022-05-31 06:52:00 +08:00
parent 96bfa3f2d3
commit c764e7097d
9 changed files with 77 additions and 4 deletions
+2 -2
View File
@@ -6,8 +6,8 @@ const config = require("./config")
const EventEmitter = require('events');
module.exports = async (app) => {
app.event = new EventEmitter()
const evList = await app.load(config.path)
evList.forEach(item => {
const list = await app.load(config.path)
list.forEach(item => {
Object.keys(item.res).forEach(key => {
//载入所有事件
app.event.on(key, item.res[key])
+3
View File
@@ -0,0 +1,3 @@
module.exports = {
path:"middleware/*.js"
}
+15
View File
@@ -0,0 +1,15 @@
/**
* 加载中间件
* 加载app/middleware文件夹下的中间件
*/
const config = require("./config")
module.exports = async (app) => {
let list = await app.load(config.path)
list = app.xe.orderBy(list, "res.sort")
list = list.filter(item => item.res.use)
list.forEach(item => {
app.use(async (ctx, next) => {
return await item.res.fun(ctx, next)
})
})
}
+3
View File
@@ -0,0 +1,3 @@
module.exports = {
path:"app/*/io/*.js",
}
+42
View File
@@ -0,0 +1,42 @@
/**
* socket.io
* 自动绑定io文件夹内js文件
* 参考文档:
* 1.https://socket.io/docs/v4/server-api
* 2.https://juejin.cn/post/6844903810050031630
*/
const config = require("./config")
const path = require('path')
module.exports = async (app) => {
const server = require('http').createServer(app.callback());
const io = require('socket.io')(server);
let list = await app.load(config.path)
app.io = io
//默认命名空间
io.on('connection', socket => {
socket.emit('open', "连接成功!");//通知客户端已连接
console.log('通知客户端已连接');
//监听disconnect事件
socket.on('disconnect', (eventName, callback) => {
console.log('断开')
})
for (let el of list) {
//空间名称
// const namespace = path.basename(path.resolve(el.parse.dir, '..'))
//事件名称
const onname = el.parse.name
socket.on(onname, el.res)
}
});
//覆盖启动方法
app.startServer = () => {
// 监听端口
app.startServer = server.listen(3000, () => {
console.log('listening on *:3000');
});
}
}