//服务器端压缩
procedure CompressData(var CompressedStream: TMemoryStream;
const CompressionLevel: TCompressionLevel);
var
SourceStream: TCompressionStream;
DestStream: TMemoryStream;
Count: Integer;
Begin
Count := CompressedStream.Size;
DestStream := TMemoryStream.Create;
SourceStream:=TCompressionStream.Create(CompressionLevel, DestStream);
Try
CompressedStream.SaveToStream(SourceStream);
//将原始流进行压缩, DestStream中保存着压缩后的流
SourceStream.Free;
CompressedStream.Clear;
//写入原始流的尺寸
CompressedStream.WriteBuffer(Count, SizeOf(Count));
//写入经过压缩的流
CompressedStream.CopyFrom(DestStream, 0);
finally
DestStream.Free;
end;
end;
//客户端解压
procedure UnCompressData(var CompressedStream: TMemoryStream);
var
SourceStream: TDecompressionStream;
DestStream: TMemoryStream;
Buffer: PChar;
Count: integer;
Begin
CompressedStream.Position:=0;
CompressedStream.ReadBuffer(Count, SizeOf(Count));
GetMem(Buffer, Count);
DestStream := TMemoryStream.Create;
SourceStream := TDecompressionStream.Create(CompressedStream);
Try
SourceStream.ReadBuffer(Buffer^, Count);
DestStream.WriteBuffer(Buffer^, Count);
SourceStream.Free;
DestStream.Position := 0;//复位流指针
CompressedStream.LoadFromStream(DestStream);
finally
FreeMem(Buffer);
DestStream.Free;
end;
end;
//服务器端使用时
ms := TMemoryStream.Create;
ms.Position := 0;
CompressData(ms, clFastest);
ms.Free;
//客户端使用时
ms := TMemoryStream.Create;
ms.Position := 0;
UnCompressData(ms);
ms.Free;
我这样用N长时间了都没问题的