节点套接字应用程序新实例作用

这是一个简单的套接字应用程序使用事件库模式

const invitation = require('./invitation'); module.exports = function(io){ io.on('connection', (socket)=>{ var prepareGame = new PrepareGame(socket) socket.on("sendInvitation",(data, ack)=>{ prepareGame.sendInvitation(data,ack) }); }); } 

并在prepareGame.js

 const events = require('events'); const util = require('util'); class PrepareGame extends events { constructor(socket) { super(); this.user = socket.user var self = this draftInvitation(data){ this.newInvitation = { from_user: self.user.id, to_user: data.to_user, message:data.message, created_at:moment().unix(), } return this }; self.on("toSocket", (eventName, clientId, data) => { console.log(` ===>>>> sending to listener ${eventName}`, clientId); var client = users[clientId] if(client) client.emit(eventName, data) }); } // public function sendInvitation(data, ack) { // console.log(this); var self = this data.message = 'New Invitation' draftInvitation(data) .emit("toSocket", "getInvitation", data.to_user, self.newInvitation) setTimeout(()=>{ data.message = 'Invitation timeout' draftInvitation(data) .emit("toSocket", "getInvitation", self.user.id, self.newInvitation) }, 15000) if(typeof ack == 'function') ack({ status:200, message: "invitation sent", }) } } util.inherits(PrepareGame, events.EventEmitter ) module.exports = PrepareGame 

代码是不同devise模式的总和。 它工作正常,但我有一些疑问

  1. io.connection调用一次连接到套接字并创buildprepareGame实例。 考虑两个用户的两个实例,那么sendInvitation如何在调用时自动绑定正确的实例
  2. 套接字断开时,新的prepareGame实例会发生什么?
  3. 我想从socket.on中删除(data, ack)=>{ } encloser它意味着它应该socket.on(“sendInvitation”,prepareGame.sendInvitation)然后如何在sendInvitation函数中pipe理这个引用