Finkes
Finkes

Reputation: 516

nodejs: are TCP messages sent/received atomically?

Consider following example:

server:

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');
});

client:

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');
});

Is it guaranteed that the message 'Hello World!\r\n' from the client will be received atomically in one message when client.on('data', ...) is called? Or do I have to store all messages in a temporary buffer and specify my own "start" and "end" pattern to recognize that a complete message was received?

Upvotes: 1

Views: 63

Answers (1)

hassansin
hassansin

Reputation: 17508

No, its not guaranteed with TCP protocol. TCP is streaming protocol, which means it could accumulate multiple write()s in your code in internal TCP buffer. It writes those chunks in order and doesn't respect your message boundaries.

Same thing happens in the client end. You could receive multiple write() chunks in one data event.

You need to implement your own protocol to identify each message. Google for tcp message boundary problem to find some implementation examples.

Upvotes: 3

Related Questions