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

(编辑:jimmy 日期: 2024/11/18 浏览:2)

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中的使用实例代码详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!