2012-06-29 54 views
3

我已經構建了一個簡單的TCP服務器,並需要將客戶端輸入與存儲在變量中的硬編碼字符串進行比較。字符串比較失敗

但是,data == username總是失敗。

爲什麼?我能做些什麼呢?

的例子:

var authenticateClient = function(client) { 
    client.write("Enter your username:"); 
    var username = "eleeist"; 
    client.on("data", function(data) { 
     if (data == username) { 
      client.write("username success"); 
     } else { 
      client.write("username failure"); 
     } 
    }); 
} 

var net = require("net"); 
var server = net.createServer(function(client) { 
    console.log("Server has started."); 
    client.on("connect", function() { 
     console.log("Client has connected."); 
     client.write("Hello!"); 
     authenticateClient(client); 
    }); 
    client.on("end", function() { 
     console.log("Client has disconnected."); 
    }); 
}).listen(8124); 
+0

'data'包含什麼?它最後是否包含換行符? – Sjoerd

+0

我不確定。我試圖將它與'eleeist \ n'進行比較,但仍然沒有運氣。 – Eleeist

回答

4

我已經更新了你的代碼,用客戶端實現。它會工作。
在'data'事件上,回調將有Buffer類的實例。所以你必須先轉換成字符串。

var HOST = 'localhost'; 
var PORT = '8124'; 

var authenticateClient = function(client) { 
    client.write("Enter your username:"); 
    var username = "eleeist"; 
    client.on("data", function(data) { 
     console.log('data as buffer: ',data); 
     data= data.toString('utf-8').trim(); 
     console.log('data as string: ', data); 
     if (data == username) { 
      client.write("username success"); 
     } else { 
      client.write("username failure"); 
     } 
    }); 
} 

var net = require("net"); 
var server = net.createServer(function(client) { 
    console.log("Server has started."); 
    client.on("connect", function() { 
     console.log("Client has connected."); 
     client.write("Hello!"); 
     authenticateClient(client); 
    }); 
    client.on("end", function() { 
     console.log("Client has disconnected."); 
    }); 
}).listen(PORT); 

//CLIENT 
console.log('creating client'); 
var client = new net.Socket(); 
client.connect (PORT, HOST, function() { 
    console.log('CONNECTED TO: ' + HOST + ':' + PORT); 
    client.write('eleeist\n');  
}); 
client.on('data', function(data) { 
    console.log('DATA: ' + data); 
    // Close the client socket completely 
    // client.destroy(); 
}); 

client.on('error', function(exception){ console.log('Exception:' , exception); }); 
client.on('timeout', function() { console.log("timeout!"); }); 
client.on('close', function() { console.log('Connection closed'); }); 
+0

而不是使用'toString',你應該在流上調用'setEncoding'。然後'數據'事件會自動被字符串觸發,如果字符串是UTF8,它們將被正確處理。 – loganfsmyth