socketのeggにおける使用例コードの詳細


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);
 ap/io
ap/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!');

 };
};
 ap/io/middleware/filter.js

module.exports = (app) => {
 return async (ctx, next) => {
  // console.log(ctx.packet);
  await next();
  // console.log('packet response!');
 };
};
ap/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での使用例コードの详しい解です。皆さんに助けてほしいです。もし何か疑问がありましたら、メッセージをください。小编はすぐに返事します。ここでも私たちのサイトを応援してくれてありがとうございます。