-1

我正在尝试在 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:无法调用未定义的方法“写入”

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

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

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

有什么办法可以处理套接字所属的对象吗?

recvHHCPmsg() 函数是这样定义的:

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

1 回答 1

0

改变

this.socket.write

this.write

在函数调用内部,当前指向thissocket对象只是对象。当我尝试在本地机器上进行此更改时,我得到了

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);
});
于 2013-09-29T18:29:18.650 回答