Search code examples
delphiudpindydelphi-10-seattle

Indy UDP sending and responding simple strings


I am using Delphi 10.0 Seattle.

I'd like to send requests to a UDP server and then read the server response, which is a simple string:

Client side:send('12345')
server side(onread event or whatever):if received string =  ('12345') then 
send ('jhon|zack|randy')
else disconnect;

The length of the response string is variable.

The server is running on a well opened network with open connection (dedicated vps). The client is not the same, it is behind routers and secure networks (not forwarded).

So far, I can only send the request from the client:

(uc=idUDPclient)

procedure TForm1.Button1Click(Sender: TObject);
var
  s:string;
begin
  if uc.Connected =False then
    Uc.Connect;
  uc.Send('12345');
  uc.ReceiveTimeout := 2000;
  s:=uc.ReceiveString() ;
  ShowMessage(s);
  uc.Disconnect
end;

Server side (us=idUDPserver)

procedure TForm1.usUDPRead(AThread:TIdUDPListenerThread;const AData: TIdBytes;ABinding: TIdSocketHandle);
begin
  ShowMessage(us.ReceiveString());

  if us.ReceiveString() = '12345' then
  begin
    ShowMessage(us.ReceiveString());

    //respond with a string to the client immediately (behind a routers) how ?
  end;

I don't know if TCP is better, and how to use it.

Android will be involved.


Solution

  • You are not using the TIdUDPServer.OnUDPRead event correctly. You need to get rid of the calls to ReceiveString(), they do not belong in there. Use the AData parameter instead, it contains the raw bytes of the client's request. TIdUDPServer has already read the client's data before firing the event handler.

    If you need the bytes in a string, you can use Indy's BytesToString() function, or IIdTextEncoding.GetString() method.

    To send a response back to the client, use the ABindingparameter.

    Try this:

    procedure TForm1.usUDPRead(AThread: TIdUDPListenerThread;
      const AData: TIdBytes; ABinding: TIdSocketHandle);
    var
      s: string;
    begin
      s := BytesToString(AData);
      //ShowMessage(s);
      if s = '12345' then begin
        ABinding.SendTo(ABinding.PeerIP, ABinding.PeerPort, 'jhon|zack|randy', ABinding.IPVersion);
      end;
    end;