2
var net = require('net');
var HOST = '0.0.0.0';
var PORT = 5000;
// Create a server instance, and chain the listen function to it
// The function passed to net.createServer() becomes the event handler for the 'connection' event
// The sock object the callback function receives UNIQUE for each connection
net.createServer(function(sock) {
// We have a connection - a socket object is assigned to the connection automatically
console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
// Add a 'data' event handler to this instance of socket
sock.on('data', function(data) {
console.log('DATA ' + sock.remoteAddress + ': ' + data);
// Write the data back to the socket, the client will receive it as data from the server
if (data === "exit") {
console.log('exit message received !')
}
});
// Add a 'close' event handler to this instance of socket
sock.on('close', function(data) {
console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
});
}).listen(PORT, HOST);
console.log('Server listening on ' + HOST +':'+ PORT);
無論我怎麼努力,我不能讓:節點JS讀取TCP套接字特定消息net.createServer
if (data === "exit") {
console.log('exit message received !')
}
的工作,它總是假的。
我通過telnet連接併發送「退出」,服務器應該進入「if」循環並說「退出消息收到」。這從來沒有發生,有人可以擺脫一些光?謝謝
編碼提示是正確的。但它仍然不能可靠地工作,因爲套接字可能不會一次發送完整的請求字節。 「退出」可能分佈在幾個接收到的緩衝區中,或可能包含在也包含其他數據的緩衝區中。 – Matthias247
你說的對,很多變量可能發生在應該被處理的輸入數據中,但爲了解決他的問題,telnet不會把他的字符串「退出」,它太小了。 – shuji