Joshua
Joshua

Reputation: 1737

Exception on reading broadcast data with TIdUDPServer (Indy 10) using Delphi 7

I'm having problems trying to use OnUDPRead Event of TIdUDPServer to read broadcast Data sent from a IdUDPClient Client I created. I've tried using the examples shown in the following questions but to no avail.

How can I send a broadcast message in Delphi

Reading data with TIdUDPServer

I'm able to bind TIdUDPServer to the port I specify:

procedure TForm1.Button1Click(Sender: TObject);
begin
  IdUDPServer1.BroadcastEnabled := True;
  IdUDPServer1.DefaultPort := StrToInt(edit2.Text);
  IdUDPServer1.Bindings.Add.IP := '0.0.0.0';
  //IdUDPServer1.ThreadedEvent:=True;
  IdUDPServer1.Active := True;
end;

IdUDPServer1UDPRead is triggered successfully showing that the UDP Server is working, but I get an exception at this line -> DataStringStream.CopyFrom(AData, AData.Size);

Exception:Access violation at address 004BA415 in module 'IndyUDPReceiver.exe'. Read of address 74736574

procedure TForm1.IdUDPServer1UDPRead(Sender: TObject;
  AData: TStream; ABinding: TIdSocketHandle);
var
  DataStringStream: TStringStream;
  msg: string;
begin
  try
    DataStringStream := TStringStream.Create('');
    try
      DataStringStream.CopyFrom(AData, AData.Size);
      msg := DataStringStream.DataString;
      Memo1.Lines.Add(msg);
    finally
      DataStringStream.Free;
    end;
  except
    on E: Exception do
    begin
      Memo1.Lines.Add('Exception:' + E.Message);
      DataStringStream.Free;
    end;
  end;
end;

I've uploaded the full Client and Server to: http://www.2shared.com/file/5SRweGIa/Indy_UDP.html

Grateful for any pointers. :)

Upvotes: 0

Views: 6119

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596582

Did you, by chance, upgrade your project from an older version of Delphi and/or Indy, and forget to check your event handlers for signature changes? The TIdUDPServer.OnUDPRead event stopped using TStream for its AData parameter a long time ago. It was switched to using TIdBytes instead:

procedure TForm1.IdUDPServer1UDPRead(AThread: TIdUDPListenerThread; const AData: TIdBytes; ABinding: TIdSocketHandle);
var
  msg: string;
begin
  msg := BytesToString(AData, Indy8BitEncoding);
  Memo1.Lines.Add(msg);
end;

A few weeks ago, we had to change the AData parameter for XE3 to finally address an RTTI incompatibility between Delphi and C++ in all 2009+ versions:

procedure TForm1.IdUDPServer1UDPRead(AThread: TIdUDPListenerThread; const AData: array of Byte; ABinding: TIdSocketHandle);
var
  msg: string;
begin
  msg := BytesToString(AData, Indy8BitEncoding);
  Memo1.Lines.Add(msg);
end;

Upvotes: 2

Related Questions