2

I want to send a broadcast UDP message in my LAN, the application is client/server.

I desire to update the user interface, this way any computer send a message to update the others. Can I use UDPServer indy, how to use ? Thanks

Jean Ambrosio
  • 21
  • 1
  • 1
  • 2
  • Note that UDP is unreliable - see http://en.wikipedia.org/wiki/User_Datagram_Protocol#Comparison_of_UDP_and_TCP - "When a message is sent, it cannot be known if it will reach its destination; it could get lost along the way. There is no concept of acknowledgment, retransmission or timeout." – mjn Sep 15 '11 at 07:28
  • Instead of UDP I would use a TCP client socket connection which listens for server messages in a thread. A heartbeat protocol can be used to detect client or server side disconnect. – mjn Jan 08 '15 at 08:31

2 Answers2

5

Create two applications, one represents the sender and the other the receiver.

Sender

Drop a TIdUDPClient and a TButton component on your form. On the OnClick handler of the button write:

procedure TfrmUDPClient.BroadcastClick(Sender: TObject);
begin
  UDPClient.Broadcast('Test', 8090);
end;

Receiver

Drop a TIdUDPServer on your form, define the same port (8090) for it and add this to the OnUDPRead handler:

procedure TfrmUDPServer.UDPServerUDPRead(Sender: TObject; AData: TStream; ABinding: TIdSocketHandle);
var
  DataStringStream: TStringStream;
  Msg: String;
begin
  DataStringStream := TStringStream.Create('');
  try
    DataStringStream.CopyFrom(AData, AData.Size);
    Msg := DataStringStream.DataString;
  finally
    DataStringStream.Free;
  end;
  ShowMessage(Msg);
end;

Or, in later versions of Indy:

procedure TfrmUDPServer.UDPServerUDPRead(AThread: TIdUDPListenerThread;
  const AData: TIdBytes; ABinding: TIdSocketHandle);
var
  Msg: String;
begin
  try
    {if you actually sent a string encoded in utf-8}
    Msg := TEncoding.UTF8.GetString(AData);
  except
  end;

  ShowMessage(Msg);
end;

To test, run both applications and click on the button. To test with two or more "listeners" you have to use another machine. That is, you can't run multiple listeners on the same IP.

Millie Smith
  • 4,536
  • 2
  • 24
  • 60
Josir
  • 1,282
  • 22
  • 35
  • 1
    You can actually can have more than one UPD Listeners on the same ip, see here http://stackoverflow.com/questions/2604826/multicast-messages-to-multiple-clients-on-the-same-machine – Christopher Chase Sep 15 '11 at 05:10
  • 2
    Switch `Active` and `BroadcastEnabled` to `true` on the Components in Delphi7! – Grim Aug 13 '16 at 06:30
  • 1
    Additionally, you should set `Active` to `true` only after setting your bindings! https://stackoverflow.com/a/40795379/2850543 – Millie Smith Aug 19 '18 at 05:30
3

Create a TIdUDPServer or TIdUDPClient component. Both have Broadcast methods that should do exactly what you need.

Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467