var
  a: array[0..5] of Char;
  p: PChar;
begin
  New(p);
  p := 'bruce';
  a := 'bruce';
  Dispose(p);
end;p和a有什么区别?
比如用TIdUDPServer的SendBuffer方法
IdUDPServer.SendBuffer('192.168.1.245', 2050, P, 6);

IdUDPServer.SendBuffer('192.168.1.245', 2050, a, 6);
有什么区别?为什么我使用TIdUDPServer进行信息的收发时用数组做Buffer进行收发一切正常,而使用PChar做buffer进行收发时收到的却是乱码?源程序如下://============================================================//
发送部分:
procedure TForm1.BtnSendClick(Sender: TObject);
var
  Buf: array[0..99] of Char;
//  P: PChar;
begin
//  New(P);
  if (Trim(Edtdaddress.Text) = '') or (Trim(EdtdPort.Text) = '') then Exit;  try
    StrCopy(Buf, PChar(EdtMsg.Text));
    IdUDPServer.SendBuffer(Edtdaddress.Text, StrToInt(EdtdPort.Text), Buf, Length(EdtMsg.Text) + 1);
//    StrCopy(P, PChar(EdtMsg.Text));
//    IdUDPServer.SendBuffer(Edtdaddress.Text, StrToInt(EdtdPort.Text), P, Length(EdtMsg.Text) + 1);
  except
    LbStatus.Caption := 'ERROR';
  end;
//  Dispose(P);
end;
//============================================================//
接收部分:用PChar做buffer时接收到的是乱码,而且提示执行到Dispose(P)后出现指针操作错误。而使用字符数组时一切正常。
procedure TForm1.IdUDPServerUDPRead(Sender: TObject; AData: TStream;
  ABinding: TIdSocketHandle);
var
  Buf: array[0..99] of Char;
  P: PChar;
  S: string;
begin
  StrCopy(Buf, '');
//  New(P);
  try
//    AData.ReadBuffer(P, AData.Size);
    AData.ReadBuffer(Buf, AData.Size);
  except
    LbStatus.Caption := 'ERROR';
  end;  S := '[IP: ' + ABinding.PeerIP +']  [Port: ' + IntToStr(ABinding.PeerPort) +']';
  S := S + '  [Data: ' + StrPas(Buf) + ']';
//  S := S + '  [Data: ' + StrPas(P) + ']';
  EdtdPort.Text := IntToStr(ABinding.PeerPort);  Memo1.Lines.Add(S);
//  Dispose(P);
end;端口使用的是2010在局域网里的测试。开始就是用的string做Buffer,收到的是乱码,后来用pchar也不行
后来用字符数组做buffer发送才可以用的是Delphi7,TIdUDPServer控件
client和server端都是用的它做收发,程序也一样

解决方案 »

  1.   

    改:
    IdUDPServer.SendBuffer('192.168.1.245', 2050, P, 6);
    为:
    IdUDPServer.SendBuffer('192.168.1.245', 2050, P[1], 6);—————————————————————————————————
    宠辱不惊,看庭前花开花落,去留无意;毁誉由人,望天上云卷云舒,聚散任风。
    —————————————————————————————————
      

  2.   

    这样好像不行,字符array和shortstring类型作为buffer发送才OK