这个java代码的等效nodejs代码

时间:2014-10-18 06:06:51

标签: java node.js

我遇到了这个java代码, 链接: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
}

我只是想知道它们是否是node.js中的等效代码?

1 个答案:

答案 0 :(得分:0)

来自套接字的read 4个字节convert that to a 32-bit signed big endian integer,然后读取更多字节:

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