获取ObjectOutputStream/ObjectInputStream的进度
我最近了解了如何使用 ObjectOutputStream 和 ObjectInputStream 通过服务器和客户端之间的简单 Java 套接字连接发送对象。我想知道如果我想传输一个可能很大的对象,例如图像,是否可以放置一个线程来跟踪已发送/接收的数据量的进度?如果这个问题的答案不是很直接,有人可以解释我如何做类似的事情吗?提前致谢!
I recently figured out how to use ObjectOutputStream and ObjectInputStream to send objects over a simple Java socket connection between a server and a client. I was wondering if I wanted to transfer an object that might be large in size, for example an image, is it possible to put a thread that keeps track of the progress of how much data has been sent/received? If the answer to this question isn't very direct, could someone explain how I might go about doing something similar? Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Apache Commons IO 库有一对类 <代码>CountingInputStream和
CountingOutputStream
实现字节计数输入/输出流过滤器。如果将它们插入流链中,您可以跟踪读取或写入的字节数。 (这些过滤器必须插入到物理输入/输出流和对象流之间的某个位置。)
您可以通过子类化
FilterInputStream
和FilterOutputStream
类。甚至还有一个名为ProgressMonitorInputStream< 的 Swing 类/code>
可能完全实现您所需要的。
The Apache Commons IO library has a pair of classes
CountingInputStream
andCountingOutputStream
that implement byte counting input/output stream filters.If you insert these into your stream chains you can track the number of bytes read or written. (These filters have to be inserted somewhere between the physical input/output stream and object stream.)
You could implement the same thing yourself by subclassing the
FilterInputStream
andFilterOutputStream
classes. And there is even a Swing class calledProgressMonitorInputStream
that might implement exactly what you need.我建议编写仪器化的InputStream和OutputStream,它们只是通过管道传入/传出构造时提供的流,同时计算经过的字节数。
然后,您可以使用插入的上述内容之一来构建流链 - 只是要小心,在检测的 OutputStream 和网络之间不要有太多缓冲区,否则您将计算进入缓冲区而不是进入网络的字节。
您还可以通过编写另一个输出流来计算要发送的总字节数,该输出流只会丢弃数据,并通过检测的输出流将对象写入一次。
I would suggest writing instrumented InputStream and OutputStream which just pipe to/from streams provided at construction time while counting the number of bytes going through.
Then you can build your stream chain with one of the above inserted -- just be careful not to have too many buffers between your instrumented OutputStream and the network, or you'd be counting bytes going into the buffers rather than into the network.
You can also use count the total bytes to be sent, by writing yet another output stream which just throws the data away and writing your objects once to it through your instrumented output stream.