根据你所说的关于该消息的什么补它,这是一个办法做到这一点:
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,则此方法将不起作用。
如果不知道您收到的消息类型,很难给出答案。它是文本吗?,二进制数据?是固定长度吗?你也编程服务器?在大多数情况下需要一个协议。 –
@ja_mesa它是二进制数据。前四个字节用于写入消息长度,后四个字节用于CRC32校验和。 – bvitaliyg