Compressing and decompressing streams

2019-02-21 19:44发布

问题:

I found this article about simple proxy server implemented in JAVA:

http://www.java2s.com/Code/Java/Network-Protocol/Asimpleproxyserver.htm

The code simply gets some stream from the client, after sends it to the server and after it gets stream from the server and sends the response to the client. What I would like to do is to compress this streams before it is sent and decompress after it is received.

I found the class GZIPInputStream but I'm not sure how to use it and what I found on internet didn't help me. I either didn't understand that so much or it was not a good solution for me.

My idea is too that but I'm not sure if its ok:

final InputStream streamFromClient = client.getInputStream();
final OutputStream streamToClient = client.getOutputStream();
final InputStream streamFromServer = server.getInputStream();
final OutputStream streamToServer = server.getOutputStream();

InputStream gzipStream = new GZIPInputStream(streamFromClient );
try
{
        while ((bytesRead = gzipStream.read(request)) != -1)
       {
                    streamToServer.write(request, 0, bytesRead);
                    streamToServer.flush();
        }
}
catch (Exception e) {
System.out.println(e);
}

Now the data sent to the server should be compressed before sending (but I'm not sure if it's a correct solution). IS IT?

Now imagine the server sends me the compressed data. So this stream:

final InputStream streamFromServer = server.getInputStream();

is compressed.

How can I decompress it and write to the

final OutputStream streamToClient = client.getOutputStream();

Thanks for the help, guys!

回答1:

Read the javadoc of these streams : http://download.oracle.com/javase/6/docs/api/java/util/zip/GZIPInputStream.html and http://download.oracle.com/javase/6/docs/api/java/util/zip/GZIPOutputStream.html.

GZIPOutputStream compresses the bytes you write into it before sending them to the wrapped output stream. GZIPInputStream reads compressed bytes from the wrapped stream and returns uncompressed bytes.

So, if you want to send compressed bytes to anyone, you must write to a GZIPOutputStream. But of course, this will only work if the receiving end knows it and decompresses the bytes it receives.

Similarly, if you want to read compressed bytes, you need to read them from a GZIPInputSTream. But of course, it'll only work if the bytes are indeed compressed using the same algorithm by the sending end.