为TCustomWinSocket定义Helper类是否安全?

时间:2013-03-14 15:14:09

标签: delphi winsock

为了让我更方便地读/写代码,我把所有这些功能都堆成了一个帮助类,所以我可以在客户/服务器主单元中避免所有这些愚蠢的功能,我把它放在一个单元中这是由两个主要单位导入的,所以我只想确保我在这里做错了。

所以例如,当我在ServerSocket事件中时,我可以像这样使用它:

Socket.SendString();

  { Extend TCustomWinSocket to make it more comfterable to read and tidy code }
  TCustomWinSocketHelpher = class Helper for TCustomWinSocket
  private
    procedure SendStringLenth(StrLen: Integer);
  public
    function ReceiveStringLength: Integer;
    function ReceiveString(const StrLen: Integer): String;
    function ReceiveStream(StreamLen: Integer; Callback: TUpdateProgBarProc): TMemoryStream;

    procedure SendString(const Str: string);
    procedure SendStreamEx(ASendStream: TStream);
  end;

(*************************** TCustomWinSocketHelpher BEGIN ***************************)

function TCustomWinSocketHelpher.ReceiveString(const StrLen: Integer): String;
var
  S: UTF8String;
begin
  SetLength(S, StrLen);
  ReceiveBuf(PAnsiChar(S)^, StrLen);
  Result := UTF8ToString(S);
end;

function TCustomWinSocketHelpher.ReceiveStringLength: Integer;
begin
  ReceiveBuf(Result, SizeOf(Result));
  Result := ntohl(Result);
end;

function TCustomWinSocketHelpher.ReceiveStream(StreamLen: Integer; Callback: TUpdateProgBarProc): TMemoryStream;
const
  ChunkSize = 4096;
var
  PData: PByte;
  ReadAmount: Integer;
begin
  Result := TMemoryStream.Create;
  GetMem(PData, ChunkSize);
  try
    while StreamLen > 0 do
    begin
      ReadAmount := ReceiveBuf(PData^, Min(ChunkSize, StreamLen));
      if (ReadAmount > 0) then
      begin
        Result.WriteBuffer(PData^, ReadAmount);
        Callback(ReadAmount); // update gui
        Dec(StreamLen, ReadAmount); // update loop condition
      end else
      begin
        OutputDebugString(PChar('ReadAmount ' + Inttostr(ReadAmount)));
      end;
    end;
  finally
    FreeMem(PData);
  end;
end;

procedure TCustomWinSocketHelpher.SendStringLenth(StrLen: Integer);
begin
  StrLen := htonl(StrLen);
  SendBuf(StrLen, SizeOf(StrLen));
end;

procedure TCustomWinSocketHelpher.SendString(const Str: string);
var
  S: UTF8String;
  Len: Integer;
begin
  S := UTF8Encode(Str);
  Len := Length(S);
  SendStringLenth(Len);
  SendBuf(PAnsiChar(S)^, Len);
end;

procedure TCustomWinSocketHelpher.SendStreamEx(ASendStream: TStream);
begin
  ASendStream.Position := 0;
  SendStream(ASendStream);
end;

(*************************** TCustomWinSocketHelpher END ***************************)

1 个答案:

答案 0 :(得分:2)

是的,定义帮助程序类是完全安全的。