kannanrbk
kannanrbk

Reputation: 7134

TCP Socket send data in GZIP Compression format

I am sending MultiPart content to my remote server to store it in filesystem. For this I am using Java TCP/IP protocol. For avoiding network bandwidth and TCP Input / Output buffer memory , I am sending the data in GZIP compressed format. But , I cannot decompress the data received from the client. I got Unexpected end of ZLIB input stream Exception. Its due to the server is receiving data in chunks.

Java Code

Client

  OutputStream out = new GZIPOutputStream(sock.getOutputStream());
  byte[] dataToSend = FileUtil.readFile(new File("/Users/bharathi/Downloads/programming_in_go.pdf"));
  out.write(dataToSend);

Server

    out = new FileOutputStream("/Users/bharathi/Documents/request_trace.log");
    InputStream in = new GZIPInputStream(clntSocket.getInputStream());
    int totalBytesRead = 0;
    int bytesRead;
    byte[] buffer = new byte[BUFFER_SIZE];

    while ((bytesRead = in.read(buffer)) != -1)
    {
        out.write(buffer , 0 , bytesRead);
        totalBytesRead += bytesRead;
    }

Is there any solution to send the data in GZIP compressed format in Socket?

Upvotes: 3

Views: 4974

Answers (2)

pmoleri
pmoleri

Reputation: 4451

Try adding:

out.flush();
sock.shutdownOutput();

to your client code.

Upvotes: 0

Noam Rathaus
Noam Rathaus

Reputation: 5588

GZIPOutputStream generates a GZIP file format, meaning that the other end has to receive the complete stream (which is a file) before it can process it, this is the reason for your error.

If you are looking to actually do a stream based data transfer, drop gzip, and go for zlib, I believe Zlib compression Using Deflate and Inflate classes in Java answers how to do this.

Upvotes: 3

Related Questions