config/config.default.js
= exports.io { the init: {}, namespace : { ' / ' : {// corresponding to Lane router.js of ( '/') connectionMiddleware: [ ' the auth ' ], // the corresponding IO / Middleware / the 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 / I
app/io/middleware/auth.js
/ * * * The Created by Bear ON 2018/2/12. * / Const the PREFIX = ' Room ' ; // define the room number module.exports = App => { return the async (CTX, Next) => { const {App, Socket, Logger, Helper} = CTX; const ID = socket.id; const NSP = app.io.of ( ' / ' ); const Query = socket.handshake.query; // user information const {Room, the userId} = query; // get socket link pass over the parameters const Rooms is =[Room]; the console.log (Room, the userId); const the tick = (ID, MSG) => { logger.debug ( ' #tick ' , ID, MSG); // send a message the user before playing socket.emit ( ID, helper.parseMsg ( ' the deny ' , MSG)); // call the user kick adapter method, client disconnect event trigger nsp.adapter.remoteDisconnect (ID, to true , ERR => { logger.error (ERR); } ); }; // check whether there is room, the user does not exist kicked // NOTE: irrelevant here app.redis with the insert, can be used instead of other storage const . = hasRoom the await app.redis GET(The PREFIX} {$ `:` $ {} Room); the console.log (hasRoom, the PREFIX} {$ `:` $ {Room}) // IF (hasRoom!) { // the tick (ID, { // type : 'deleted', // Message: '. deleted, has been deleted Room', // }); // return; // } // users logger.debug ( ' #join ' , Room); socket.join (Room); // list of online nsp.adapter.clients (Rooms, (ERR, Clients) => { // update the list of online users 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; };