I am sending images through sockets using ByteArrayOutputStreams like this.
ImageIO.write(image, "gif", byteArrayO);
byte [] byteArray = byteArrayO.toByteArray();
Connection.pw.println("" + byteArray.length);
int old = Connection.client.getSendBufferSize();
Connection.client.setSendBufferSize(byteArray.length);
Connection.client.getOutputStream().write(byteArray, 0, byteArray.length);
Everything works OK, the image is like 130kb in the end, and I receive it like this
int nbrToRead = Integer.parseInt(slave.input.readLine().trim());
int old = slave.socket.getReceiveBufferSize();
slave.socket.setReceiveBufferSize(nbrToRead);
byte[] byteArray = new byte[nbrToRead];
int nbrRd = 0;
int nbrLeftToRead = nbrToRead;
while (nbrLeftToRead > 0) {
int rd = slave.socket.getInputStream().read(byteArray, nbrRd, nbrLeftToRead);
if (rd < 0)
break;
nbrRd += rd;
nbrLeftToRead -= rd;
}
ByteArrayInputStream byteArrayI = new ByteArrayInputStream(byteArray);
BufferedImage img = ImageIO.read(byteArrayI);
It works well, but every image sent the memory heap of java increases like 50 mb. I have tried setting the receivebuffersize, but it still stays up. It goes to maximum in heap, then stays for a while then stops.
How can I clear the buffer so when it has received the bytes it will dispose of them?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…