1

我有一个使用 TCP 套接字连接的服务器和一个客户端。在客户端(用 C++ 编写)我使用zlib库压缩一个字符串(str):

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());

然后我将它发送到服务器。这是我将压缩字符串写入套接字的代码行:

int bytesWritten = write(sockfd, &compressedString, compressedStringLength);

在服务器(用 C# 编写)上,我从套接字接收压缩字节流并使用 DeflateStream 类对其进行解压缩:

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);

这是解压功能:

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;
 }

压缩过程和通过套接字发送压缩字节有效,但我在上面的解压缩函数的行中遇到异常decompressor.CopyTo(output);:System.IO.InvalidDataException:块长度与其补码不匹配。

有人知道问题是什么,我该如何解决?

编辑:我已经尝试在解压过程开始前跳过前两个字节。

4

0 回答 0