TIdTCPServer / TIdTCPClient:传输RawByteString的最佳方法是什么?

时间:2017-04-08 15:05:34

标签: delphi indy indy10 tcpserver rawbytestring

我正在寻找最快的(股票市场应用,非常时间关键)解决方案,用于从 TIdTCPServer 传输大量加密的RawByteString数据(最多500条记录/秒)到 TIdTCPClient

最好的方法是什么?

提前致谢!

修改

在我的项目中,我需要使用n'软件库来加密字符串。最快的加密方法返回RawByteString。从理论上讲,我只应将CodePage设置为加密字符串并将其转换为UTF8编码,但我的所有尝试都失败了。

在我看来最合乎逻辑的是:

服务器:

var
  rbs: RawByteString;
begin
  rbs := EncryptString(AInput, DEFAULT_ENCRYPTION_KEY);
  SetCodePage(rbs, 65001, true);
  AContext.Connection.IOHandler.WriteLn(rbs, IndyTextEncoding_UTF8);
  ...
end;

客户端:

var
  rbs: string;
  Output: string;
begin
  rbs := IdTCPClient1.IOHandler.ReadLn(IndyTextEncoding_UTF8);
  Output := DecryptString(rbs, DEFAULT_ENCRYPTION_KEY);
  ...
end;

1 个答案:

答案 0 :(得分:0)

将二进制加密的RawByteString转换为UTF-8字符串是完全错误的,无论它有多快。使用Indy 10传输二进制数据的最佳方法是使用TIdBytesTStream代替。 IOHandler具有两者的读/写方法,例如:

var
  rbs: RawByteString;
begin
  rbs := EncryptString(AInput, DEFAULT_ENCRYPTION_KEY);
  AContext.Connection.IOHandler.Write(Int32(Length(rbs)));
  AContext.Connection.IOHandler.Write(RawToBytes(PAnsiChar(rbs)^, Length(rbs)));
  ...
end;

var
  buf: TIdBytes;
  rbs: RawByteString;
  Output: string;
begin
  IdTCPClient1.IOHandler.ReadBytes(buf, IdTCPClient1.IOHandler.ReadInt32);
  SetLength(rbs, Length(buf));
  BytesToRaw(buf, PAnsiChar(rbs)^, Length(rbs));
  Output := DecryptString(rbs, DEFAULT_ENCRYPTION_KEY);
  ...
end;

可替换地:

var
  rbs: RawByteString;
  strm: TIdMemoryBufferStream;
begin
  rbs := EncryptString(AInput, DEFAULT_ENCRYPTION_KEY);
  strm := TIdMemoryBufferStream.Create(PAnsiChar(rbs), Length(rbs));
  try
    AContext.Connection.IOHandler.LargeStream := False;
    AContext.Connection.IOHandler.Write(strm, 0, True);
  finally
    strm.Free;
  end;
  ...
end;

var
  strm: TMemoryStream;
  rbs: RawByteString;
  Output: string;
begin
  strm := TMemoryStream.Create;
  try
    IdTCPClient1.IOHandler.LargeStream := False;
    IdTCPClient1.IOHandler.ReadStream(strm, -1, False);
    SetLength(rbs, strm.Size);
    Move(strm.Memory^, PAnsiChar(rbs)^, Length(rbs));
  finally
    strm.Free;
  end;

  { alternatively:

  SetLength(rbs, IdTCPClient1.IOHandler.ReadInt32);
  strm := TIdMemoryBufferStream.Create(PAnsiChar(rbs), Length(rbs));
  try
    IdTCPClient1.IOHandler.ReadStream(strm, Length(rbs), False);
  finally
    strm.Free;
  end;
  }

  Output := DecryptString(rbs, DEFAULT_ENCRYPTION_KEY);
  ...
end;