根据您对消息所说的内容,这是一种方法:
in = socket.getInputStream();
byte[] buff = new byte[4096];
int packLen=0;
int ret=0;
while(!isInterrupted()) {
int offset=0;
int bLeft=4;
// 99% of the times the read will return 4 bytes,
// but just in case, put it in a loop.
while (bLeft > 0) {
ret = in.read(buff, offset, bLeft);
if (ret > 0) {
bLeft-=ret;
offset+=ret;
}
else if (ret == 0) {
// socket has been closed
}
else {
// soket has an error
}
}
// convert the 4 bytes to an int, depends on the way it's was sent
// this method is used frecuently
packLen = (int)((buff[0] & 0xff) << 24) |
(int)((buff[1] & 0xff) << 16) |
(int)((buff[2] & 0xff) << 8) |
(int)(buff[3] & 0xff);
// if the 4 bytes of the CRC32 is not included in the length,
// increment the length
packLen+=4;
offset=4;
if (packLen > 4092)
{
// packet is too big, ignore it or do something else
packLen=4092;
}
bLeft=packLen;
// Noew loop until the whole mesage has been read
while (bLeft > 0) {
ret = in.read(buff, offset, bLeft);
if (ret > 0) {
bLeft-=ret;
offset+=ret;
}
else if (ret == 0) {
// socket has been closed
}
else {
// soket has an error
}
}
// the readChunk function must be change
// Need to pass the length of the message.
// Is not the buff.length anymore
readChunk(buff, packLen+4 /* +4 for the length of the message*/);
}
如果你需要一个 Java CRC32 类,我可以给你,它符合 PKZIP 和以太网标准。
编辑:注意:如果数据包长度大于 4096,则此方法将不起作用。