2016-01-27 96 views
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」循環並說「退出消息收到」。這從來沒有發生,有人可以擺脫一些光?謝謝

回答

1

這是因爲數據不是字符串,如果您嘗試與===進行比較,您將因爲類型不匹配而變爲false。 要解決這個問題,您應該將數據對象與簡單的==進行比較,或者在綁定數據事件之前使用socket.setEncoding('utf8')。

https://nodejs.org/api/net.html#net_event_data

var net = require('net'); 
var HOST = '0.0.0.0'; 
var PORT = 5000; 

net.createServer(function(sock) { 
    console.log('CONNECTED:',sock.remoteAddress,':',sock.remotePort); 
    sock.setEncoding("utf8"); //set data encoding (either 'ascii', 'utf8', or 'base64') 
    sock.on('data', function(data) { 
     console.log('DATA',sock.remoteAddress,': ',data,typeof data,"===",typeof "exit"); 
     if(data === "exit") console.log('exit message received !'); 
    }); 

}).listen(PORT, HOST, function() { 
    console.log("server accepting connections"); 
}); 

注意。 如果收到的數據會很大,您應該在它的末尾連接並處理消息比較。檢查其他的問題來處理這些情況:

Node.js net library: getting complete data from 'data' event

+0

編碼提示是正確的。但它仍然不能可靠地工作,因爲套接字可能不會一次發送完整的請求字節。 「退出」可能分佈在幾個接收到的緩衝區中,或可能包含在也包含其他數據的緩衝區中。 – Matthias247

+0

你說的對,很多變量可能發生在應該被處理的輸入數據中,但爲了解決他的問題,telnet不會把他的字符串「退出」,它太小了。 – shuji