Click to See Complete Forum and Search --> : Compress Object Across Socket Stream


mlahiff
August 17th, 1999, 02:14 PM
HELP!!!

I am attempting to compress a Vector of Strings and send them across a socket to the client.

Inserting a GZIPInputStream/GZIPOutputStream anywhere before the ObjectInputStream/ObjectOutputStream forces the applet to block. I have tried any combination I can think of (differing orders, subclassing the GZIPInputStream, etc), without success.

It seems others have gotten this to work, based upon conversations in other threads in other newsgroups, but I haven't figured out the secret yet! Any help is GREATLY appreciated!

Best Regards,

Martin LaHiff
martin_lahiff@hp.com

SWThomas
August 19th, 1999, 06:12 PM
Martin asks: I am attempting to compress a Vector of Strings and send them across a socket to the client.

This little program works for me:, substituting a file for the socket.


import java.io.*;
import java.util.Vector;
import java.util.zip.*;

class GZTest {
static Vector outstrings = new Vector(4);
static Vector instrings;

public static void main(String args[])
throws Exception {
outstrings.add("First");
outstrings.add("Second");
outstrings.add("Third");
outstrings.add("Fourth");

ObjectOutputStream out =
new ObjectOutputStream(
new GZIPOutputStream(
new FileOutputStream("Data.gz")));
out.writeObject(outstrings);
out.close();

ObjectInputStream in =
new ObjectInputStream(
new GZIPInputStream(
new FileInputStream("Data.gz")));

instrings = (Vector)in.readObject();

System.out.println("Input = " + instrings.toString());
}
}




Note that the Object streams are wrapped around the Gzip streams.

On output, the ObjectOutputStream encodes the objects into a stream. The GZIPOutputStream then compresses the stream and the FileOutputStream writes it to the file.

On input, the FileInputStream reads from the file, the GZIPInputStream decompresses it, producing the correct input for the ObjectInputStream to decode.

If you don't want to close() the stream, you should at least drain() it, and possibly flush() it. Note that if you don't flush() occasionally, you will have a "memory leak" in a long-running program, because the ObjectOutputStream keeps a hash of every object you have written through it since the last flush().

=Spencer