访问在socket.io中发出消息的套接字

我有一个名为GameServer的类,它具有处理各种socket.io消息的方法。 这里是一个简单的例子:

var GameServer = function(app, io) { this.app = app; this.io = io; this.io.on('connection', this.handleConnect.bind(this)); }; GameServer.prototype.handleConnect = function(socket) { socket.on('receive_a_message', this.handleMessage.bind(this)); }; GameServer.prototype.handleMessage = function(message) { this.app.doSomethingWithMessage(message); // here is where I want to reply/emit to the socket that sent me the message }; 

不幸的是,因为我需要绑定()我的socket.iocallback方法,以便访问其他类属性(在上面的例子中,我需要访问this.app运行doSomethingWithMessage),我在不同的上下文。

有没有办法让我的socket.iocallback绑定到我的GameServer类,仍然访问发送我的消息的套接字? 任何人都可以看到解决这个问题的工作?

你已经在绑定中传递上下文了。 您也可以将套接字作为绑定的一部分来传递。

 var GameServer = function(app, io) { this.app = app; this.io = io; this.io.on('connection', this.handleConnect.bind(this)); }; GameServer.prototype.handleConnect = function(socket) { socket.on('receive_a_message', this.handleMessage.bind(this, socket)); }; GameServer.prototype.handleMessage = function(socket, message) { this.app.doSomethingWithMessage(message); socket.emit('a reply'); };