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

时间:2014-07-09 22:41:59

标签: javascript node.js 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
};

不幸的是,因为我需要bind()我的socket.io回调方法才能访问其他类属性(在上面的例子中,我需要访问this.app来运行doSomethingWithMessage),我在不同的上下文中。

有没有办法让我将socket.io回调绑定到我的GameServer类并仍然访问发送我的消息的套接字?任何人都可以看到解决这个问题的方法吗?

1 个答案:

答案 0 :(得分:2)

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

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');
};
相关问题