如何正确封装套接字.输入输出插座

How do I properly encapsulate a socket.io socket?

本文关键字:输入输出 插座 套接字 封装 何正确      更新时间:2023-09-26

这段代码在我的node.js服务器应用程序中运行:

io.sockets.on('connection', function (socket) {
    var c = new Client(socket, Tools.GenerateID());
    waitingClients.push(c);
    allClients.push(c);
    if (waitingClients.length === 2)
    {
        activeGames.push(new Game([waitingClients.pop(), waitingClients.pop()]));
    }
});
function Client(socket, id)
{
    this.Socket = socket;
    this.ID = id;
    this.Player = new Player();
    this.Update = function(supply)
    {
        socket.emit('update', { Actions: this.Player.Actions, Buys: this.Player.Buys, Coins:  this.Player.Coins, Hand: this.Player.Hand, Phase: this.Player.Phase, Supply: supply});
    }
    socket.on('play', function(data) {
        console.log(data);
        console.log(this.Player);
    });
    socket.emit('id', id);
}

我遇到麻烦的部分是'play'事件的事件处理程序。console.log(this.Player)输出undefined。我有点理解为什么它是错误的,因为"this"指的是我的客户端对象(套接字?匿名函数?),但我不知道如何重新安排代码来正确处理'play'事件,并完全访问客户端对象的成员。

您只需要将this存储在Client中的其他变量中。

function Client(socket, id)
{
    var self = this;
    ...
    socket.on('play', function(data) {
        self.Player.play();
    });