lavokad
lavokad

Reputation: 137

asynchronous node.js concepts with IO

var net = require ('net'),
local_port = 8000,
local_ip = '127.0.0.1',
remote_port = 80,
remote_ip = 'xxx.xx.xx.x',

server = net.createServer (function (socket){
  var serviceSocket = new net.Socket ();
  serviceSocket.connect (parseInt (remote_port), remote_ip, function () {
    socket.on ('data', function (msg){
      serviceSocket.write (msg);
    });
  });
}).listen (local_port, local_ip);

There is SERVER, which runs this code, and CLIENT, which connects to SERVER and sends two blocks of data one after another, D1 and then D2.

Is it true, that D2 will always arrive before D1 to remote_ip?

Wouldn't a case like this be possible:

Let's say CLIENT sends D1 of size x asynchronously, and then D2 of size y, where y is much smaller than x, wouldn't then socket.on('data'...) fire first with the reception of D2 on its 'data' listener?

Upvotes: 0

Views: 50

Answers (1)

Hargo
Hargo

Reputation: 1266

net.createServer and net.Socket both create TCP sockets.

This has a few implications:

  1. Data you write first will be received first.
  2. Boundaries are not fixed, that is a single write on one side may be split into multiple data events on the receiving side, or vise versa multiple write calls may become a single data event. The only guarantee is that the data will remain in the same order you write it.

If you're interested in unordered (and unreliable) data you could look at node's dgram module http://nodejs.org/api/dgram.html which creates UDP sockets, but for most cases you want TCP.

Upvotes: 1

Related Questions