I have a server and a client connecting using TCP socket. At the client (which is written in C++) I compress a string (str) using the zlib library:
uLongf compressedStringLength = compressBound(str.length());
Bytef* compressedString = new Bytef[compressedStringLength];
const Bytef* originalString = reinterpret_cast<const Bytef*>(str.c_str());
compress(compressedString, &compressedStringLength, originalString, str.length());
Then I send it to the server. This is the line of code where I write the compressed string to the socket:
int bytesWritten = write(sockfd, &compressedString, compressedStringLength);
At the server (which is written in C#) I recieve the stream of the compressed bytes from the socket and decompress it using the DeflateStream class:
NetworkStream stream = getStream(ref server); //server is a TcpListener object which is initialized to null.
byte[] bytes = new byte[size];
stream.Read(bytes, 0, size);
Stream decompressedStream = Decompress(bytes);
This is the Decompress function:
private static Stream Decompress(byte[] input)
{
var output = new MemoryStream();
using (var compressStream = new MemoryStream(input))
using (var decompressor = new DeflateStream(compressStream, CompressionMode.Decompress))
{
decompressor.CopyTo(output);
}
output.Position = 0;
return output;
}
The compressing process and sending the compressed bytes over the socket works, but I get an exception at the line decompressor.CopyTo(output);
at the Decompress function above: System.IO.InvalidDataException: Block length does not match with its complement.
Does someone know what the problem is and how can I solve it?
EDIT: I`ve already tried to skip the first two bytes brfore the start of the decompression process.