这不是显示/演示问题。这是与数据传输协议有关的问题。Socket 是一种面向流的协议,这意味着它不是基于消息的。同时,您正在使用它,就像它是基于消息的一样 - 您可以这样做,但是您需要为您的发送者和接收者定义一个协议,以识别每条消息的开始和结束。
话虽如此,并根据您的要求,我假设您已决定使用换行符(或换行符的某种变体)作为消息结束标记。为了使这项工作正常工作,您需要主动在传入数据中查找该换行符,以便您可以识别每条消息的结尾并在处理之前将其剥离。
以下代码应替换您的 socket.on 方法以获得您想要的结果。
// define your terminator for easy reference, changes
var msgTerminator = '\n';
// create a place to accumulate your messages even if they come in pieces
var buf;
socket.on('data', function(data){
// add new data to your buffer
buf += data;
// see if there is one or more complete messages
if (buf.indexOf(msgTerminator) >= 0) {
// slice up the buffer into messages
var msgs = buf.split(msgTerminator);
for (var i = 0; i < msgs.length - 2; ++i) {
// walk through each message in order
var msg = msgs[i];
// pick off the current message
console.log('Data in server, sending to handle()');
// send only the current message to your handler
worker.handle(msg, socket);
}
buf = msgs[msgs.length - 1]; // put back any partial message into your buffer
}
});