请考虑以下示例:
服务器
var net = require('net');
var server = net.createServer(function(connection) {
console.log('client connected');
connection.on('end', function() {
console.log('client disconnected');
});
connection.write('Hello World!\r\n');
connection.pipe(connection);
});
server.listen(8080, function() {
console.log('server is listening');
});
客户端:
var net = require('net');
var client = net.connect({port: 8080}, function() {
console.log('connected to server!');
});
client.on('data', function(data) {
console.log(data.toString());
client.end();
});
client.on('end', function() {
console.log('disconnected from server');
});
当 客户端时,是否保证客户端的消息 'Hello World!\ r \ n' 会在一条消息中以原子方式接收.on('data',...) 被调用?或者我是否必须将所有消息存储在临时缓冲区中并指定我自己的“开始”和“结束”模式以识别是否收到了完整的消息?
答案 0 :(得分:0)
不,TCP协议无法保证。 TCP是流协议,这意味着它可以在内部TCP缓冲区的代码中累积多个write()
。它按顺序写入这些块并且不尊重您的消息边界。
同样的事情发生在客户端。您可以在一个write()
活动中收到多个data
块。
您需要实现自己的协议来识别每条消息。 Google tcp message boundary problem
找到了一些实施示例。