我正在尝试在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();
}
};
答案 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);
});