0

I came across to this java code, LINK: java socket send & receive byte array

Socket socket = ...
DataInputStream dIn = new DataInputStream(socket.getInputStream());

int length = dIn.readInt();                    // read length of incoming message
if(length>0) {
    byte[] message = new byte[length];
    dIn.readFully(message, 0, message.length); // read the message
}

And I was just wondering if their is an equivalent code for this in node.js ??

Community
  • 1
  • 1
Miguel Lorenzo
  • 560
  • 1
  • 5
  • 12

1 Answers1

0

Just read 4 bytes from the socket, convert that to a 32-bit signed big endian integer, and then read that many more bytes:

function readLength(cb) {
  var length = socket.read(4);
  if (length === null)
    socket.once('readable', function() { readLength(cb); });
  else
    cb(length.readInt32BE(0, true));
}

function readMessage(cb) {
  readLength(function retry(len) {
    var message = socket.read(len);
    if (message === null)
      socket.once('readable', function() { retry(len); });
    else
      cb(message);
  });
}

// ...

readMessage(function(msg) {
  // `msg` is a Buffer containing your message
});
mscdex
  • 104,356
  • 15
  • 192
  • 153
  • What if your using nodejs TCP server ?? – Miguel Lorenzo Oct 18 '14 at 07:44
  • Then you just write your data to the socket. You can [write the length](http://nodejs.org/docs/latest/api/buffer.html#buffer_buf_writeint32be_value_offset_noassert) to a Buffer that you write to the socket. – mscdex Oct 18 '14 at 14:35