我应该与一个控制器进行通信,该控制器的端口被配置为发送状态数据。我应该使用NodeJS阅读特定IP的端口2424。 我尽力而为,没有任何东西可读。 以下是我的困惑: *我没有收到“连接”事件 - 这可能是因为在控制器级实现的接口非常简单?或者没有建立连接 *在nodejs套接字中没有“读取”方法 - 只是一个从未收到任何东西的on('data')。如何在NodeJS中读取TCP端口/套接字?没有“读取”方法
我提到,我也没有听,因为我的应用程序是一个客户端在任何连接不走,只是连接到服务接收数据
我的代码是这样的:
var host = 'xxx.yyy.zzz.ttt';
var port = 2424;
var client = net.connect({port:port, host:host}, function() {
log.logOut(ModName, '[checkPortaRack] Client connected.');
});
client.setTimeout(SOCKET_TIMEOUT * 1000);
client
.on('timeout', function() {
client.destroy();
callback(new Error("No data received. So device '"+dev.name+"' in error"));
})
.on('connect', function() {
log.logOut(ModName, '[checkPortaRack] Connected...');
})
.on('data', function(chunk) {
data += chunk;
console.log(data.toString());
log.logOut(ModName, 'Got data...');
client.destroy();
})
.on('end', function() {
data = data.toString().replace('\u0000',"");
log.logOut(ModName, 'Data: '+JSON.stringify(data));
console.log('client disconnected');
})
.on('error', function(e) {
status.deviceDown = true;
log.logOut(ModName, "[checkPortaRack][Device Error]["+dev.name+"] ERROR Getting data from device: " + e.message);
callback(new Error("Error while receiving data. So device '"+dev.name+"' in error"));
});
该负责人发出这样的C#代码,他们认为这简直妙不可言:
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
System.Diagnostics.Debug.WriteLine("catch");
//a socket error has occured
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
System.Diagnostics.Debug.WriteLine("Client Disconnected");
break;
}
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
}
tcpClient.Close();
}
所以,问题是:我怎么能读这个IP /端口,利用节点的插座,没有一个“读”的方法和没有发送“连接”事件?
非常感谢, 克特林
什么节点版本您使用的? – mscdex
另外,你有没有得到任何事件? – mscdex
@mscdex:使用节点v0.8.21 – Catalin