无法调用未定义的方法'write'

时间:2013-09-29 18:22:41

标签: javascript node.js sockets typeerror

我正在尝试在Node.js上创建一个类似客户端的TCP套接字,并使其连接到服务器:

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.'); });
});

但是我得到了这个错误(在'this.socket.write'行):

TypeError:无法调用未定义的方法'write'

从创建连接时使用的功能,我可以看出它正在识别主机和连接。 那么为什么我不能用套接字发送数据呢?

编辑:这个问题已经解决,但是有一个新问题......

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.
});

有没有办法用套接字所属的对象做事?

这是recvHHmsms()函数的定义方式:

User.prototype.recvHHCPmsg = 
function(text)
{
    if (text == 'disconnect')
    {
        this.socket.write('disconnect');
        this.socket.end();
        this.socket.destroy();
    }
};

1 个答案:

答案 0 :(得分:0)

更改

this.socket.write

this.write

在函数调用中,this指向的当前对象仅为socket对象。当我在本地机器上尝试这个改变时,我得到了

Connected to HHCP server.
Data sent.

修改

要使recvHHCPmsg可访问,请执行以下操作。

更改

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

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