egg-socket.io安装和通讯

  • Post author:
  • Post category:其他



安装

npm i egg-socket.io --save

config/plugin.js

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

config/config.default.js

config.io = {
  init: {
    wsEngine: 'ws',
  },
  namespace: {
    '/': {
      connectionMiddleware: [],
      packetMiddleware: [],
    }
  },
  redis: {
    host: '127.0.0.1',
    port: 6379,
    db: 0,
  },
};

egg部署: package.json start和dev里面添加 –sticky

 "scripts": {
    "start": "egg-scripts start --sticky --daemon --title=egg-server-yunwei",
    "stop": "egg-scripts stop --title=egg-server-yunwei",
    "dev": "egg-bin dev --sticky",
    "debug": "egg-bin debug",
    "test": "npm run lint -- --fix && npm run test-local",
    "test-local": "egg-bin test",
    "cov": "egg-bin cov",
    "lint": "eslint .",
    "ci": "npm run lint && npm run cov",
    "autod": "autod"
  },

uniapp导入uni-socket.io.js文件

socketUrl:"http://192.168.43.31:7001",

引入io

//引入io通讯库
import io from '../common/uni-socket.io.js';

配置连接

import Vue from 'vue'
import Vuex from 'vuex'

//引入io通讯库
import io from '@/assets/common/uni-socket.io.js';
Vue.use(Vuex)

export default new Vuex.Store({
  state: { },
  actions: {
	  //连接socket
	          connectSocket({state,dispatch}){
	              const S= io('http://127.0.0.1:7001',{
	                  query:{},
	                  transports:['websocket'],
	                  timeout:5000  //超时
	              })
	              //监听连接
	              S.on('connect',()=>{
	                  console.log('已连接')
	                  //测试推送一条消息到后端
	                  S.emit('test','123456')
	                  //唯一的id
	                  //console.log(S.id)
	                  //前端接收 后端传过来的数据
	                  S.on(S.id,(e)=>{
	                      console.log(e)
	                  })
	              })
	              //监听失败
	              S.on('error',()=>{
	                  console.log('连接失败')
	              })
	              //监听断开
	              S.on('disconnect',()=>{
	                  console.log('已断开')
	              })
	          },



  }
})

后台配置路由

app/io/controller/nsp.js 测试

'use strict';

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

class NspController extends Controller {
  async test() {
    const {ctx,app}=this
    //接收前端传递过来的信息 参数
    //console.log(ctx.args)
    let message=ctx.args[0]
    //当前的socket连接
    const socket=ctx.socket
    const id=socket.id
    socket.emit(id,'哈哈哈')
  }
}

module.exports = NspController;

路由 router.js

'use strict';

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  //解构io
  const { router, controller,io } = app;
  //这里的'test'要和前端的'test'一致
  io.of('/').route('test',io.controller.nsp.test);



版权声明:本文为weixin_45086164原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。