当前位置: 首页 > 工具软件 > electron-egg > 使用案例 >

egg使用egg-socket.io

蒲功
2023-12-01

下载

npm i egg-socket.io --save

使用
plugin.js

module.exports.io = {
    enable: true,
    package: 'egg-socket.io',
}

// config.default.js

 config.io = {
        init: { }, // passed to engine.io
        namespace: {
            '/': {
                connectionMiddleware: ['connection'],
                packetMiddleware: [],
            },
            '/example': {
                connectionMiddleware: ['connection'],
                packetMiddleware: [],
            },
        },
    }

// router/io.js

module.exports = app => {
    const { io } = app;
    io.of('/').route('CHAT_SEND', io.controller.chat.chat)
    io.of('/').route('CHATVIDEO_REQ', io.controller.chat.videoReq)
}

// router.js

 require('./router/io')(app)

// controller/chat.js

const Controller = require('egg').Controller;

class chat extends Controller {
   async chat() {
       const { ctx, app } = this;
       const usocket = app.usocket.getState()
       let info = ctx.args[0]
       const message = ctx.args[1];
   }
   // 视频聊天请求
   async videoReq() {
       const { ctx, app } = this;
       const usocket = app.usocket.getState()
       let info = ctx.args[0]
    }
}
module.exports = chat;

需要前端配合使用socket-client

 类似资料: