Delphi中对服务器的访问冲突

时间:2012-11-21 19:40:55

标签: delphi tcp memorystream

尝试通过TMemoryStream编写简单的客户端和服务器来接收/发送数据。当我在客户端btnTestClick中按下按钮时,会出现错误 Access violation at address 005D5581 in module 'Client.exe'. Write of adress 00000000。我做错了什么?

顺便说一句,客户端服务器连接工作正常我很简单IdTCPClient1Connected函数正在编写'Client Connected!'

客户端代码

procedure TForm1.btnTestClick(Sender: TObject);
var
  msRecInfo: TMemoryStream;
  arrOf: array of Integer; i:integer;
begin
  for i := 0 to 10 do
    arrOf[i]:=random(100);

  msRecInfo:= TMemoryStream.Create;

  try
    msRecInfo.Write(arrOf, SizeOf(arrOf));
    idTCPClient1.IOHandler.Write(msRecInfo);
  finally
     msRecInfo.Free;
  end;

end;

end

服务器代码

procedure TForm1.IdTCPServer1Execute(AContext: TIdContext);
var
   msRecInfo: TMemoryStream;
  arrOf: array of Integer; i:integer;
begin
  msRecInfo:= TMemoryStream.Create;
  try
    AContext.Connection.IOHandler.ReadStream(msRecInfo, -1, False);

    msRecInfo.Position := 0;
    msRecInfo.Read(arrof, SizeOf(arrof));
  finally
    memo1.Lines.Add(IntToStr(arrOf[1]));
    msRecInfo.Free;
  end;
  //AContext.Connection.IOHandler.ReadStream(msRecInfo, SizeOf(arrOf));
  //msRecInfo.Read(arrOf, sizeOf(arrOf));
end;

1 个答案:

答案 0 :(得分:5)

在为其分配任何元素之前,您开始写入动态数组。动态数组不会像您可能习惯的那样自动增长。你需要先设置它们的长度。

如果你没有设置动态数组的长度,那么它只是一个空指针,这解释了为什么你在地址0处获得访问冲突。

更改你的btnTestClick方法:

var
  msRecInfo: TMemoryStream;
  arrOf: array of Integer;
  i: integer;
begin
  SetLength(arrOf, 11);
  for i := 0 to 10 do
    arrOf[i] := Random(100);