繁体   English   中英

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

[英]Accessing the socket that emitted a message in 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.io回调方法bind()来访问其他类的属性(在上面的示例中,我需要访问this.app来运行doSomethingWithMessage),所以我处于另一个上下文中。

有没有办法将我的socket.io回调绑定到我的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');
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM