Come faccio ad applicare la tua ultima soluzione in questo caso?
Qui non utilizza buffer.
Dovrebbe funzionare per leggere i pacchetti, vero?
codice:
protected byte[] readSourcePacket() throws IOException {
// Protocol is straightforward: 1 size byte, <n> data bytes
byte[] size = readN(1);
if (size[0] == 0)
throw new IOException("0-byte packet");
byte[] read = readN(size[0] & 0xff);
//Dump.dump("reading", read);
return read;
}
protected byte[] readN(int n) throws IOException {
byte[] data = new byte[n];
int offset = 0;
// A timeout would be nice, but there's no obvious way to
// write it before java 1.4 (probably some trickery with
// a thread and closing the stream would do the trick, but...)
while (offset < n) {
int count = is.read(data, offset, n - offset);
if (count == -1)
throw new IOException("end-of-stream");
offset += count;
}
return data;
}