簡體   English   中英

node js 從 tcp socket net.createServer 讀取特定消息

[英]node js read specific message from tcp socket net.createServer

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);

無論我嘗試什么,我都無法得到:

    if (data === "exit") {
        console.log('exit message received !')
    }

工作,它總是假的。

我通過 telnet 連接並發送“exit”,然后服務器應該進入“if”循環並說“exit message received”。 這永遠不會發生,有人可以解釋一下嗎? 謝謝

那是因為 data 不是字符串,如果您嘗試與 === 進行比較,則會得到 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 網絡庫:從“數據”事件中獲取完整數據

我知道這是一篇很老的帖子,當我嘗試在這個問題的答案中實現代碼時,無論使用了“==”還是 utf8 編碼,我都遇到了同樣的問題。 我的問題原來是我使用的客戶端在退出消息的末尾附加了一個 '\\n' 字符,從而導致服務器上的字符串比較失敗。 也許這不是 telnet 等的問題,但 netcat 就是這種情況。 希望這對遇到這篇文章並遇到與我相同問題的其他人有所啟發。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM