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);
app/io
app/io/middleware/auth.js
/** *Createdbybearon2018/2/12. */ constPREFIX='room';//定义房间号 module.exports=app=>{ returnasync(ctx,next)=>{ const{app,socket,logger,helper}=ctx; constid=socket.id; constnsp=app.io.of('/'); constquery=socket.handshake.query; //用户信息 const{room,userId}=query;//获取socket链接传过来的参数 constrooms=[room]; console.log(room,userId); consttick=(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与插件无关,可用其他存储代替 consthasRoom=awaitapp.redis.get(`${PREFIX}:${room}`); console.log(hasRoom,`${PREFIX}:${room}`) //if(!hasRoom){ //tick(id,{ //type:'deleted', //message:'deleted,roomhasbeendeleted.', //}); //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','packetreceived!'); awaitnext(); console.log('disconnect!'); }; };
app/io/middleware/filter.js
module.exports=(app)=>{ returnasync(ctx,next)=>{ //console.log(ctx.packet); awaitnext(); //console.log('packetresponse!'); }; };
app/io/controller/chat.js
/** *Createdbybearon2018/2/12. */ module.exports=app=>{ classchatControllerextendsapp.Controller{ asyncindex(){ this.ctx.socket.emit('res','test'); } asyncmessage(){//方法通过客户端this.emit('message',{})//触发 this.ctx.socket.emit('message','test'); constparams=this.ctx.args[0]; //this.ctx.service.message.sendPeerMessage(params); console.log(2,params); } asynconline(){//modelMessage.sendOfflineMessage(socket,data.userId); } } returnchatController; };
总结
以上所述是小编给大家介绍的socket在egg中的使用实例代码详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!