Search code examples
delphitcpindyaccess-violation

Why do I get an AccessViolation in Indy Sockets 9 IdTcpServer ServerExecute?


First Question:

Is the following routine a correct implementation of an Indy 9 IdTcpServer.OnExecute routine?

procedure TMyConnServer.ServerExecute(AContext: TIdPeerThread);
var
  buffSize: integer;
  str:      string;
begin
  AContext.Connection.ReadFromStack(True, 600, False);
  buffSize := AContext.Connection.InputBuffer.Size;
  if (buffSize > 0) then
    { Extract input buffer as string }
    str := AContext.Connection.ReadString(buffSize);

    { Notify connection object of received data }
    if (AContext.Data <> nil) then
    begin
      TConnectionHandler(AContext.Data).Read(str);
    end;
  end;
end;

Second (actually more important) Question:

Now there is occasionally an access violation (read from address 000000). Obviously in the line:

  AContext.Connection.ReadFromStack(True, 600, False);

but checking if AContext / Connection / InputBuffer / IOHandler = nil BEFORE is false. AFTER the call (and after the exception was raised) the IOHandler is nil.

We are using RAD Studio / Delphi 2007.


Solution

  • The only way the IOHandler can become nil like you describe is if another thread in your app called Disconnect() on the connection while your worker thread was still running.