我應該與一個控制器進行通信,該控制器的端口被配置爲發送狀態數據。我應該使用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