我有一个任务。从 InputStream 我应该收到多部分消息。前四个字节是消息长度,其他字节是消息体。同时可以接收多条消息。例如:1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16
有
1,2,3,4 - length(in this case 4), 3,4,5,6 - body
7,8,9,10 - length (6), 11,12,13,14,15,16 - body
等等
我用这种方法计算的长度:
public static int byteArrayToInt(byte[] paRawBytes, int piOffset, boolean pbBigEndian) {
int iRetVal = -1;
if(paRawBytes.length < piOffset + 4)
return iRetVal;
int iLowest;
int iLow;
int iMid;
int iHigh;
if(pbBigEndian)
{
iLowest = paRawBytes[piOffset + 3];
iLow = paRawBytes[piOffset + 2];
iMid = paRawBytes[piOffset + 1];
iHigh = paRawBytes[piOffset];
}
else
{
iLowest = paRawBytes[piOffset];
iLow = paRawBytes[piOffset + 1];
iMid = paRawBytes[piOffset + 2];
iHigh = paRawBytes[piOffset + 3];
}
// Merge four bytes to form a 32-bit int value.
iRetVal = (iHigh << 24) | (iMid << 16) | (iLow << 8) | (0xFF & iLowest);
return iRetVal;
}
和更多:
private static void getEventsList(byte[] bytesFromInputStream) {
int start = 4;
int end = getLength(bytesFromInputStream) + 4;
byte[] tmp;
tmp = Arrays.copyOfRange(bytesFromInputStream, start, end);
eventsArrayList.add(tmp);
if (bytesFromInputStream.length > end) {
byte[] newArray = Arrays.copyOfRange(bytesFromInputStream, end, bytesFromInputStream.length);
getEventsList(newArray);
}
}
private static short getLength(byte[] bytes) {
return ByteUtils.byteArrayToInt(Arrays.copyOfRange(bytes, 0, 4), 0, true);
}
但它不起作用,我没有更多的想法。请帮帮我