I have the next piece of code
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');});
}
}
Everytime a connection is made I get
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)
This has something to do with evenHandler()
of course. I don't understand how objects are created in Node JS and their scope. Where were socket
and data
created, for example? what is their scope?
Thanks a lot
This means the current calling function.
In your case this refers to eventHandler and eventHandler only has data as the accessible value.
If you try to access socket you'll get an exception like you do.Because socket is not in that function scope.
Both socket and data are coming from the asynchronous callbacks which is the main pattern for node.js.
You've got to bind
the this
value that you want the event handler functions to use like 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');});
};
}