2
votes

On server (C++), binary data is compressed using ZLib function:

compress2()

and it's sent over to client (Java). On client side (Java), data should be decompressed using the following code snippet:

public static String unpack(byte[] packedBuffer) {
    InflaterInputStream inStream = new InflaterInputStream(new ByteArrayInputStream( packedBuffer);
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    int readByte;
    try {
        while((readByte = inStream.read()) != -1) {
            outStream.write(readByte);
        }
    } catch(Exception e) {
        JMDCLog.logError(" unpacking buffer of size: " + packedBuffer.length);
        e.printStackTrace();
    // ... the rest of the code follows
}

Problem is that when it tries to read in while loop it always throws:

java.util.zip.ZipException: invalid stored block lengths

Before I check for other possible causes can someone please tell me can I compress on one side with compress2 and decompress it on the other side using above code, so I can eliminate this as a problem? Also if someone has a possible clue about what might be wrong here (I know I didn't provide too much of of the code in here but projects are rather big.

Thanks.

1
Just found this, might be helfful: jcraft.com/jzlib - Markus Kreth
Have you validated that you're getting the correct data out at the client side? Is your packedBuffer the right size, for example? - Jon Skeet
@Jon Skeet Slightly as that is the legacy code of one big system and for start I just wanted to know if I can unpack something compressed with zlib using compress2, with the java code I posted above, so I can move on with investigation of where is the problem. - passenger
@passenger: But my point is that you shouldn't be trying to diagnose this just from one side. You should look at the results of compress2(), checking the length and the data itself against what you receive in the Java code. If you're receiving the wrong data, you've got no hope of receiving it properly. - Jon Skeet
@Jon Skeet Thanks for your effort. Yes, I do know that, and that's my next step, but as this is the most easily checked and I didn't have so much experience with this in Java, I just wanted to check first if correctly compressed block with compress2 on one side can be decompressed with Java function pasted above? - passenger

1 Answers

0
votes

I think the problem is not with unpack method but in packedBuffer content. Unpack works fine

public static byte[] pack(String s) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    DeflaterOutputStream dout = new DeflaterOutputStream(out);
    dout.write(s.getBytes());
    dout.close();
    return out.toByteArray();
}

public static void main(String[] args) throws Exception {
    byte[] a = pack("123");
    String s = unpack(a);   // calls your unpack
    System.out.println(s);
}

output

123