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

时间:2021-04-24 07:37:43

I have a class named GameServer which has methods for handling various socket.io messages. Here is a brief example:

我有一个名为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
};

Unfortunately, because I need to bind() my socket.io callback methods in order to access other class properties (in the example above, I need to access this.app to run doSomethingWithMessage), I am in a different context.

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

Is there a way for me to bind my socket.io callbacks to my GameServer class and still access the socket that sent my messages? Can anyone see a work around to this problem?

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

1 个解决方案

#1


2  

You're already passing the context in a bind. You can pass the socket as part of the bind as well.

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

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');
};

#1


2  

You're already passing the context in a bind. You can pass the socket as part of the bind as well.

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

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');
};