I came across to this java code, LINK: java socket send & receive byte array
我遇到了这个java代码LINK: java socket发送和接收字节数组
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 ??
我想知道它们是否等价于这个结点的代码。js ? ?
1 个解决方案
#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:
只需从套接字中读取4个字节,将其转换为32位有符号的大端整数,然后再读取更多的字节:
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
});
#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:
只需从套接字中读取4个字节,将其转换为32位有符号的大端整数,然后再读取更多的字节:
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
});