我有下一段代码
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 中创建对象及其范围。例如,在哪里创建socket
和data
创建?他们的范围是什么?
非常感谢