-1

I am trying to make a client-like TCP socket on Node.js, and making it connect to a server:

this.socket = new net.Socket();
this.socket.setEncoding('UTF8');
this.socket.on('data', function(data)
{
    this.recvHHCPmsg(data);
});

this.socket.connect(9000, '192.198.94.227', function()
{
    //called when connection is created
    var loginCmd = 'login' + wSym + user + wSym + pass;
    console.log("Connected to HHCP server.");
    this.socket.write(loginCmd, 'UTF8', function(){ console.log('Data sent.'); });
});

But I get this error (at the 'this.socket.write' line):

TypeError: Cannot call method 'write' of undefined

From the function used when the connection is created, I can tell that it is recognizing the host and connecting. So why can't I send data with the socket?

EDIT: This problem has been solved, but there's a new one...

Okay, but I need code inside the call-back function to be able to access the object which 'owns' the socket object:
this.socket.on('data', function(data) //'this' is referring to the 'User' object
{
    this.recvHHCPmsg(data); //'this' is referring to the socket.
    //The 'User' object has a method called 'recvHHCPmsg'. 
    //I want to call that function from within this call-back function.
});

Is there any way to do things with the object that the socket belongs to?

This is how the recvHHCPmsg() function is defined:

User.prototype.recvHHCPmsg = 
function(text)
{
    if (text == 'disconnect')
    {
        this.socket.write('disconnect');
        this.socket.end();
        this.socket.destroy();
    }
};
BenMorel
  • 34,448
  • 50
  • 182
  • 322

1 Answers1

0

Change

this.socket.write

to

this.write

Inside the function call, the current object pointed by this is the socket object only. When I tried on my local machine just with this change, I got

Connected to HHCP server.
Data sent.

EDIT:

To make recvHHCPmsg accessible, do the following.

Change

this.socket.on('data', function(data) {
    this.recvHHCPmsg(data);
});

to

var self = this;
this.socket.on('data', function(data) {
    self.recvHHCPmsg(data);
});
thefourtheye
  • 233,700
  • 52
  • 457
  • 497