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 ??

1 Answer 1

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
});
Sign up to request clarification or add additional context in comments.

2 Comments

What if your using nodejs TCP server ??
Then you just write your data to the socket. You can write the length to a Buffer that you write to the socket.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.