(学)Lazarus 字符串压缩、解压缩
背景:
1、原有C#开发的WinCE系统+WebService;
2、客户说WinCE上的终端程序运行速度慢,我也说慢;
3、希望改造一个WinCE上的终端程序,因为熟悉Delphi所以Lazarus;
4、Lazarus导入的WebService代理,我看不明白,还涉及到数据类型转换神马的,决定放弃WebService;
5、打算采用lNet写个服务器,接收数据来处理和数据库之间的交互。
----------------------------------------我是分割线-----------------------------------------
解决思路:
1、Lazarus 安装 lNet组件;(这个不难)
2、把lNet中 那个Tcp示例改成多线程的;(这个也不难)
3、但数据传输过程中效率如何解决?对压缩一下!如何压缩?
a、官网上检索, http://www.lazarus.freepascal.org/index.php?topic=11552.0 ;
b、但这里面用到了 Indy组件,而这个组件点名说了,我暂时不支持WinCE;
c、找个方法把 Indy组件功能替换掉 http://topic.csdn.net/t/20041012/10/3446989.html ;
4、成功了。
代码如下:
function TFormMain.GzBase64(const s: string): string;
var OutStream, InpStream, GzStream, b64Stream: TStream;
begin
OutStream := TStringStream.Create('');
try
b64Stream := TBase64EncodingStream.Create(OutStream);
try
GzStream := Tcompressionstream.create(clmax,b64Stream);
try
InpStream := TStringStream.Create(s);
try
// Copy input stream
GzStream.CopyFrom(InpStream,InpStream.Size);
finally
InpStream.Free;
end;
finally
GzStream.Free;
end;
finally
b64Stream.Free;
end;
result := TStringStream(OutStream).DataString;
finally
OutStream.Free;
end;
end;
function TFormMain.unGzBase64(const s: string): string;
var OutStream,deCompressStream: TStream;
SL:TStringList;
begin
if(s='')
then
begin
Result:='';
abort;
end;
SL := TStringList.Create;
OutStream := TStringStream.Create(Base64ToString(s));
DecompressStream := TDecompressionStream.Create(OutStream);
try
SL.LoadFromStream(DecompressStream);
Result:=SL.Text;
finally
DecompressStream.Free;
OutStream.Free;
SL.Free;
end;
end;
function TFormMain.Base64ToString(const Value: string): string;
var
x, y, n, l: Integer;
d: array[0..3] of Byte;
Table : string;
begin
Table :=
#$40 +#$40 +#$40 +#$40 +#$40 +#$40 +#$40 +#$40 +#$40 +#$40 +#$3E +#$40
+#$40 +#$40 +#$3F +#$34 +#$35 +#$36 +#$37 +#$38 +#$39 +#$3A +#$3B +#$3C
+#$3D +#$40 +#$40 +#$40 +#$40 +#$40 +#$40 +#$40 +#$00 +#$01 +#$02 +#$03
+#$04 +#$05 +#$06 +#$07 +#$08 +#$09 +#$0A +#$0B +#$0C +#$0D +#$0E +#$0F
+#$10 +#$11 +#$12 +#$13 +#$14 +#$15 +#$16 +#$17 +#$18 +#$19 +#$40 +#$40
+#$40 +#$40 +#$40 +#$40 +#$1A +#$1B +#$1C +#$1D +#$1E +#$1F +#$20 +#$21
+#$22 +#$23 +#$24 +#$25 +#$26 +#$27 +#$28 +#$29 +#$2A +#$2B +#$2C +#$2D
+#$2E +#$2F +#$30 +#$31 +#$32 +#$33 +#$40 +#$40 +#$40 +#$40 +#$40 +#$40;
SetLength(Result, Length(Value));
x := 1;
l := 1;
while x < Length(Value) do
begin
for n := 0 to 3 do
begin
if x > Length(Value) then
d[n] := 64
else
begin
y := Ord(Value[x]);
if (y < 33) or (y > 127) then
d[n] := 64
else
d[n] := Ord(Table[y - 32]);
end;
Inc(x);
end;
Result[l] := Char((D[0] and $3F) shl 2 + (D[1] and $30) shr 4);
Inc(l);
if d[2] <> 64 then
begin
Result[l] := Char((D[1] and $0F) shl 4 + (D[2] and $3C) shr 2);
Inc(l);
if d[3] <> 64 then
begin
Result[l] := Char((D[2] and $03) shl 6 + (D[3] and $3F));
Inc(l);
end;
end;
end;
Dec(l);
SetLength(Result, l);
end;