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
+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');
});
}
}