【问题标题】:What is the proper way to use Socket.IO callbacks within classes in Node.JS?在 Node.JS 的类中使用 Socket.IO 回调的正确方法是什么?
【发布时间】:2012-07-08 09:46:37
【问题描述】:

我正在使用带有 Socket.IO 和 Express 的 Node.JS。我的目标是创建一个模块来创建自定义 Socket.IO+Express 服务器,加载我的应用程序需要的所有功能。例如,跟踪在任何给定时间连接的客户端数量。

问题是,如果可能的话,我想让服务器作为一个类工作。我已经看到其他 Node.JS 模块很好地使用类(包括 Socket.IO 本身),所以我认为它不应该与 Node 的面向模块的架构冲突。我需要它来处理类的原因是我希望能够轻松地创建服务器的多个实例。

这是我所拥有的(为简洁起见):

index.js

var myserver = require("./myserver");
var myserver1 = myserver.createServer();
var myserver2 = myserver.createServer();

myserver1.port = 8080;
myserver2.port = 8081;

myserver1.start();
myserver2.start();

myserver.js

var io = require("socket.io");
var express = require("express");
var path = require("path");

function MyServer()
{
     this.port = 8080;
     this.expressServer = null;
     this.ioServer = null;

     this.clientCount = 0;
}

Server.prototype.getClientCount = function()
{
    return this.clientCount;
}

Server.prototype.start = function()
{
    this.expressServer = express.createServer();
    this.ioServer      = io.listen(this.expressServer);
    this.expressServer.listen(this.port);

    this.ioServer.sockets.on(
        "connection",
        function()
        {
            this.clientCount++;
            console.log(this.clientCount + " clients connected.");
        }
    );
}

exports.createServer = function() { return new MyServer(); };

"connection" 回调中的代码不正确,因为 Socket.IO 回调中的this 关键字是指触发"connection" 事件的client 对象,而不是@987654326 @ 目的。那么有没有办法从回调内部访问clientCount 属性?

【问题讨论】:

    标签: node.js socket.io


    【解决方案1】:

    通过将this 复制到another 一个变量(大多数人喜欢称它为self,但有些人更喜欢that)并在您的连接处理程序中使用它来创建一个适当的闭包:

    var self=this;
    this.ioServer.sockets.on(
        "connection",
        function()
        {
            self.clientCount++;
            console.log(self.clientCount + " clients connected.");
        }
    );
    

    【讨论】:

    • 有效!为此,我之前曾尝试创建一个self 变量,但我只在构造函数中创建了它。我没有意识到它也必须在 start 方法中创建。
    猜你喜欢
    • 2023-03-10
    • 2015-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-08
    • 2011-12-31
    • 1970-01-01
    • 2012-01-19
    相关资源
    最近更新 更多