2

我有下一段代码

function Server() {

    function eventHandler(data) {
        console.log('DATA ' + this.server.socket.remoteAddress + ': ' + data);
        socket.write('You said "' + data + '"');
    }

    function connectionHandler(socket) {
        console.log('server connected');
        console.log('CONNECTED: ' + socket.remoteAddress +':'+ socket.remotePort);
        socket.on('data', eventHandler);
    }

    this.server = net.createServer(connectionHandler);

    this.port = undefined;

    this.startServer = function(port) { //Maybe change backlog for security reasons
        this.port = port;
        this.server.listen(port, function() { //'listening' listener add handle object here
            console.log('server bound');});
    }
}

每次建立连接时,我都会得到

server bound
server connected
CONNECTED: 132.65.16.64:55028

/a/fr-05/vol/netforce/stud/yotamoo/ex4/myHTTP.js:7
        console.log('DATA ' + this.server.socket.remoteAddress + ': ' + data);
                                          ^
TypeError: Cannot read property 'remoteAddress' of undefined
    at Socket.eventHandler (/a/fr-05/vol/netforce/stud/yotamoo/ex4/myHTTP.js:7:43)
    at Socket.emit (events.js:67:17)
    at TCP.onread (net.js:329:14)

evenHandler()当然是有关系的。我不明白如何在 Node JS 中创建对象及其范围。例如,在哪里创建socketdata创建?他们的范围是什么?

非常感谢

4

2 回答 2

0

这意味着当前的调用函数。

在您的情况下,这指的是 eventHandler 和 eventHandler 仅将数据作为可访问值。

如果你尝试访问套接字,你会像你一样得到一个异常。因为套接字不在那个函数范围内。

套接字和数据都来自异步回调,这是 node.js 的主要模式。

于 2012-12-06T15:56:55.247 回答
0

您已经获得了希望事件处理函数使用bind的值,如下所示:this

function Server() {

    function eventHandler(data) {
        console.log('DATA ' + this.server.socket.remoteAddress + ': ' + data);
        socket.write('You said "' + data + '"');
    }

    function connectionHandler(socket) {
        console.log('server connected');
        console.log('CONNECTED: ' + socket.remoteAddress +':'+ socket.remotePort);
        socket.on('data', eventHandler.bind(this));
    }

    this.server = net.createServer(connectionHandler.bind(this));

    this.port = undefined;

    this.startServer = function(port) {
        this.port = port;
        this.server.listen(port, function() {
            console.log('server bound');});
    };
}
于 2012-12-06T18:34:52.303 回答