Delphi Indy IdUdpClient read operation, No data returned

6.7k views Asked by At

I need to read the information that is sent by an electronic device (using UDP protocol). I am having problems using Indy components (version 9) in Delphi 7. Below you can see my code.

procedure TForm1.Button1Click(Sender: TObject);
var
  buffer: Array of Byte;
  bytes_received: integer;
begin
  SetLength(buffer, 36);
  IdUDPClient1.Host:='192.168.1.1';
  IdUDPClient1.Port:=49152;
  IdUDPClient1.BufferSize:=36;

  IdUDPClient1.Active:=True;
  IdUDPClient1.ReceiveTimeout:=50;
  bytes_received:=IdUDPClient1.ReceiveBuffer(buffer,Sizeof(buffer));
  IdUDPClient1.Active:=False;
end

The output value of "bytes_received" is 0, and obviusly, "buffer" content is not what I expect... What am I doing wrong?

Thanks in advance,

Imanol

1

There are 1 answers

1
Remy Lebeau On BEST ANSWER

Using TIdUDPClient the way you are, you are creating a static association between the remote 192.168.1.1:49152 pair and whatever random local IP/Port pair that TIdUDPClient binds to. Only packets sent from 192.168.1.1:49152 to that IP/Port can be received. The device needs to know where to send its packets to, and you need to receive them on the IP/Port that they are sent to. I don't recall offhand if TIdUDPClient has BoundIP and BoundPort properties in Indy 9, but it does in Indy 10.

ReceiveTimeout is expressed in milliseconds. Even if you have TIdUDPClient set up properly, 50ms is a very short amount of time to wait for data to arrive, so ReceiveBuffer() could simply be timing out. Try using a larger timeout value, at least a few seconds worth.

Alternatively, use TIdUDPServer instead. Set up its Bindings property with the local IP/Port pair(s) you want to receive data on, and then let its OnUDPRead event tell you whenever new data arrives from any remote IP/Port.