2012-06-29 3 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

'데이터'에는 무엇이 들어 있습니까? 끝에 개행 문자가 포함되어 있습니까? – 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'을 호출해야합니다. 그런 다음'data' 이벤트가 자동으로 문자열로 실행되고 문자열이 UTF8이면 제대로 처리됩니다. – loganfsmyth