压缩OLEVARIANT数据
TCLIENTDATASET.DATA, TCLIENTDATASET.DELTA, TDATASETPROVIDER.DATA,它们的DATA属性的类型都是OLEVARIANT。
中间层和客户端之间通过OLEVARIANT来传递数据集的数据。
为了提高数据传输的效率,发送方在传输之前可以先压缩数据,然后把压缩的数据发送给接收方。
接收方收到发送方送来的压缩数据,先进行数据解压。
使用开源的ZLIB进行数据的压缩和解压。XE2已经自带此控件,需要引用system.zlib单元。
原理:将OLEVARIANT数据流化,然后对流进行压缩,还原成OLEVARIANT以后再发送。
procedure StreamToVariant(Stream: TStream; var V: OLEVariant);
var
P : Pointer;
begin
try
V := VarArrayCreate ([0, Stream.Size - 1], varByte);
P := VarArrayLock (V);
Stream.Position := 0;
Stream.Read (P^, Stream.Size);
VarArrayUnlock (V);
except
Exit;
end;
end;
procedure VariantToStream(const V: OLEVariant; Stream: TStream);
var
P: Pointer;
begin
try
Stream.Position := 0;
Stream.Size := VarArrayHighBound (V, 1) - VarArrayLowBound (V, 1) + 1;
P := VarArrayLock (V);
Stream.Write (P^, Stream.Size);
VarArrayUnlock (V);
Stream.Position := 0;
except
Exit;
end;
end;
function CompressData(V: OleVariant): OleVariant;
var
M, M0: TMemoryStream;
begin
try
M := TMemoryStream.Create;
M0 := TMemoryStream.Create;
try
if V = Null then exit;
VariantToStream(V,M);
M.Position := 0;
ZCompressStream(M, M0);
StreamToVariant(M0, V);
finally
M.Free;
M0.Free
end;
Result := V;
except
Exit;
end;
end;
function DeCompressData(V: OleVariant): OleVariant;
var
M, M0: TMemoryStream;
begin
try
M := TMemoryStream.Create;
M0 := TMemoryStream.Create;
try
if V = Null then exit;
VariantToStream(V,M);
M.Position := 0;
ZDeCompressStream(M, M0);
StreamToVariant(M0, V);
finally
M.Free;
M0.Free
end;
Result := V;
except
Exit;
end;
end;
本文来自博客园,作者:{咏南中间件},转载请注明原文链接:https://www.cnblogs.com/hnxxcxg/archive/2012/02/26/2368612.html