【问题标题】:Cannot call method 'write' of undefined无法调用未定义的方法“写入”
【发布时间】:2013-10-05 13:45:41
【问题描述】:

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

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

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

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

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

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

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

【问题讨论】:

标签: javascript node.js sockets typeerror


【解决方案1】:

改变

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

【讨论】:

  • 感谢您帮助我解决这个问题,但我有一个新问题。见我的第一篇文章。我编辑了它。
  • @hammereditor 请说明recvHHCPmsg 的定义方式和位置。
  • 好的,我做到了。同样,它在第一篇文章中。
  • 是的。在回调内部,我希望它调用用户对象的“recvHHCPmsg”。
  • @hammereditor 不客气 :) 如果有帮助,请点赞并接受我的回答。 meta.stackexchange.com/a/5235/235416
猜你喜欢
  • 2014-03-23
  • 2013-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-08
  • 2015-06-27
相关资源
最近更新 更多