我正在尝试编写一个快速而肮脏的 tcp 服务器,但遇到了分隔符问题。根据这个问题,我正在缓冲传入的数据并寻找分隔符(在本例中为“\r\n”。但是,当我远程登录并发送消息时
foo\r\nbar
下面的服务器无法识别中间的分隔符,但确实在末尾看到了一个 \r\n - 我的印象是 telnet 只发送一个 \n 。当我通过 ruby 脚本发送消息时,任何地方都无法识别分隔符,即使消息中存在 \r\n 也是如此。
是否有一些我需要注意的 js 字符串处理行为?
var net = require("net");
var http = require('http');
var HOST = '127.0.0.1';
var PORT = 6969;
var TCP_DELIMITER = '\r\n';
var TCP_BUFFER_SIZE = Math.pow(2,16);
net.createServer(function(sock) {
console.log('CONNECTED: ' + sock.remoteAddress +':'+ sock.remotePort);
// To buffer tcp data see:
// https://stackoverflow.com/questions/7034537/nodejs-what-is-the-proper-way-to-handling-tcp-socket-streams-which-delimiter
buf = new Buffer(TCP_BUFFER_SIZE); //new buffer with size 2^16
processTCP = function(msg) {
// process messages
console.log("processTCP: "+msg);
}
// socket handlers
sock.on('data', function(data) {
// look for separator '\r\n'
console.log("data='"+data+"'");
data = data.toString('utf-8');
if(data.indexOf(TCP_DELIMITER) == -1) {
console.log("1 PART MSG, INCOMING");
buf.write(data.toString()); // write data to buffer
} else {
parts = data.toString().split(TCP_DELIMITER);
console.log("Parts: "+parts);
if (parts.length == 2) {
console.log("2 PART MSG, INCOMING");
msg = buf.toString() + parts[0]; // and do something with message
processTCP(msg);
buf = (new Buffer(TCP_BUFFER_SIZE)).write(parts[1]); // write new, incomplete data to buffer
} else {
console.log(parts.length+" PART MSG, INCOMING");
msg = buf.toString() + parts[0];
processTCP(msg);
for (var i = 1; i <= parts.length -1; i++) {
if (i !== parts.length-1) {
msg = parts[i];
processTCP(msg);
} else {
buf.write(parts[i]);
}
}
}
}
console.log('DATA ' + sock.remoteAddress + ': ' + data);
// Write the data back to the socket, the client will receive it as data from the server
sock.write('You said "' + data + '"');
});
sock.on('close', function(data) {
console.log('CLOSED: ' + sock.remoteAddress +' '+ sock.remotePort);
});
}).listen(PORT, HOST);
console.log('Server listening on ' + HOST +':'+ PORT);