Java套接字,所有写入的内容都保留在内存中 [英] Java sockets, everything written stays in memory

查看:109
本文介绍了Java套接字,所有写入的内容都保留在内存中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用像这样的ByteArrayOutputStreams通过套接字发送图像.

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);

一切正常,最终图像大约为130kb,我收到了这样的图像

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);

效果很好,但是发送给Java的内存堆的每个图像都增加了50 mb.我尝试设置receivebuffersize,但是它仍然存在.它在堆中达到最大,然后停留一段时间然后停止.

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?

推荐答案

我想到了几件事:

  • 您可能会保留对某个对象的引用,并且该引用不会被垃圾回收清理.如果正在工作的班级是单身,这是一个非常普遍的问题.
  • 确保对正在使用的任何IO类(例如BufferedInputSteam)调用close().

这篇关于Java套接字,所有写入的内容都保留在内存中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆