欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

socket在egg中的使用实例代码详解

程序员文章站 2023-12-18 12:31:58
config/config.default.js exports.io = { init: {}, namespace: { '/': {...

config/config.default.js

 exports.io = {
 init: {},
 namespace: {
  '/': {  //对应router.js里的 of('/')
  connectionmiddleware: [ 'auth' ], //对应io/middleware/auth
  packetmiddleware: [ 'filter' ],
  },
 },
 };

 config/plugin.js

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

 router.js

 io.of('/').route('chat', io.controller.chat.index);
 io.of('/').route('message', io.controller.chat.message);
 io.of('/').route('user:online', io.controller.chat.online);

 app/io

app/io/middleware/auth.js

/**
 * created by bear on 2018/2/12.
 */
const prefix = 'room'; //定义房间号

module.exports = app => {
 return async (ctx, next) => {
 const { app, socket, logger, helper } = ctx;
 const id = socket.id;
 const nsp = app.io.of('/');
 const query = socket.handshake.query;

 // 用户信息
 const { room, userid } = query; //获取socket链接传过来的参数
 const rooms = [ room ];

 console.log(room, userid);

 const tick = (id, msg) => {
  logger.debug('#tick', id, msg);
  // 踢出用户前发送消息
  socket.emit(id, helper.parsemsg('deny', msg));
  // 调用 adapter 方法踢出用户,客户端触发 disconnect 事件
  nsp.adapter.remotedisconnect(id, true, err => {
  logger.error(err);
  });
 };
 // 检查房间是否存在,不存在则踢出用户
 // 备注:此处 app.redis 与插件无关,可用其他存储代替
 
 const hasroom = await app.redis.get(`${prefix}:${room}`);
 console.log(hasroom,`${prefix}:${room}`)

 // if (!hasroom) {
 // tick(id, {
 //  type: 'deleted',
 //  message: 'deleted, room has been deleted.',
 // });
 // return;
 // }

 // 用户加入
 logger.debug('#join', room);
 socket.join(room);

 // 在线列表
 nsp.adapter.clients(rooms, (err, clients) => {
  // 更新在线用户列表
  nsp.to(room).emit('online', {
  clients,
  action: 'join',
  target: 'participator',
  message: `user(${id}) joined.`,
  });
  console.log(123,clients)
 });
 // socket.emit('connect', 'packet received!');
 
 await next();
 console.log('disconnect!');

 };
};

 app/io/middleware/filter.js

module.exports = (app) => {
 return async (ctx, next) => {
  // console.log(ctx.packet);
  await next();
  // console.log('packet response!');
 };
};

app/io/controller/chat.js

/**
 * created by bear on 2018/2/12.
 */
module.exports = app => {
 class chatcontroller extends app.controller {
 async index() {
  this.ctx.socket.emit('res', 'test');
 }
 async message() { //方法通过 客户端 this.emit('message',{})//触发
  this.ctx.socket.emit('message', 'test');
  const params = this.ctx.args[0];
  // this.ctx.service.message.sendpeermessage(params);
  console.log(2,params);
 }


 async online() {// modelmessage.sendofflinemessage(socket, data.userid);
 }
 }
 return chatcontroller;
};

总结

以上所述是小编给大家介绍的socket在egg中的使用实例代码详解,希望对大家有所帮助

上一篇:

下一篇: