Getting Progress of ObjectOutputStream/ObjectInput

2019-09-03 08:41发布

问题:

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!

回答1:

The Apache Commons IO library has a pair of classes CountingInputStream and CountingOutputStream 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 and FilterOutputStream classes. And there is even a Swing class called ProgressMonitorInputStream that might implement exactly what you need.



回答2:

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.