Record的序列化和反序列化 (delphi)

 Record的序列化和反序列化 


TDefaultMessage = record  //网络包头
    Ident: Integer;
    nIsZlib: Integer;
    nLength: Integer;
  end;


//记录转字符串
function RecordToString(var Buf; bufSize: Integer; isZlib: Boolean): string;

//字符串转记录
function StringToRecord(sData: string; var outBuf; outSize: Integer; isZlib: Boolean): Boolean;

//获取一个包
function GetNetPacket(sData: string; var defMsg: TDefaultMessage; var msgBody, msgNone: string): Boolean;


function RecordToString(var Buf; bufSize: Integer; isZlib: Boolean): string;
var
  str1: string;
begin
  SetLength(str1, bufSize);
  try
    CopyMemory(PChar(str1), PChar(@Buf), bufSize);
    if isZlib then
      Result := ZCompressStr(str1)
    else
      Result := str1;
  finally
    SetLength(str1, 0);
  end;
end;

function StringToRecord(sData: string; var outBuf; outSize: Integer; isZlib: Boolean): Boolean;
begin
  if isZlib then
    sData := ZDecompressStr(sData);

  CopyMemory(PChar(@outBuf), PChar(sData), outSize);
  Result := True;
end;

function GetNetPacket(sData: string; var defMsg: TDefaultMessage; var msgBody, msgNone: string): Boolean;
var
  len: Integer;
begin
  Result := False;
  defMsg.Ident := -1;
  msgBody := '';
  msgNone := '';
  if Length(sData) < SizeOf(TDefaultMessage) then
    Exit;

  if not StringToRecord(sData, defMsg, SizeOf(TDefaultMessage), False) then
    Exit;

  if defMsg.Ident < 0 then
    Exit;

  len := SizeOf(TDefaultMessage) + defMsg.nLength;
  if Length(sData) < len then  //包不完整
    Exit;

  if defMsg.nLength > 0 then begin
    msgBody := Copy(sData, sizeof(TDefaultMessage) + 1, defMsg.nLength);
    if defMsg.nIsZlib > 0 then
      msgBody := ZDecompressStr(msgBody);
  end;

  //剩余包
  if Length(sData) > len then
    msgNone := Copy(sData, len + 1, Length(sData) - len);

  Result := True;
end;


//demo:
procedure test1;
var
  defmsg: TDefaultMessage;
  sdata: string;
begin
  sdata:= RecordToString(defmsg, sizeof(TDefaultMessage), false);
  StringToRecord(sData, defmsg, sizeof(TdefaultMessage), false);
end;

 

你可能感兴趣的:(Delphi)