Delphi Udp ● (FRESH)

// Process the message (e.g., display in a memo) TThread.Queue(nil, procedure begin Memo1.Lines.Add(Format('[%s:%d] %s', [RemoteIP, RemotePort, ReceivedString])); end); end;

To send raw bytes:

procedure SendUDPBytes(const AHost: string; APort: Integer; const Bytes: TBytes); var UDPClient: TIdUDPClient; begin UDPClient := TIdUDPClient.Create(nil); try UDPClient.Host := AHost; UDPClient.Port := APort; UDPClient.Send(TIdBytes(Bytes)); finally UDPClient.Free; end; end; The server component operates asynchronously using the OnUDPRead event. delphi udp

type TForm1 = class(TForm) IdUDPServer1: TIdUDPServer; procedure IdUDPServer1UDPRead(AThread: TIdUDPListenerThread; const AData: TIdBytes; ABinding: TIdSocketHandle); end; procedure TForm1.IdUDPServer1UDPRead(AThread: TIdUDPListenerThread; const AData: TIdBytes; ABinding: TIdSocketHandle); var ReceivedString: string; RemoteIP: string; RemotePort: Integer; begin ReceivedString := TEncoding.UTF8.GetString(AData); RemoteIP := ABinding.PeerIP; RemotePort := ABinding.PeerPort; // Process the message (e

Introduction User Datagram Protocol (UDP) is a connectionless, lightweight transport layer protocol. Unlike TCP, UDP does not guarantee delivery, order, or error checking beyond the basic checksum. However, this simplicity makes it exceptionally fast and efficient for scenarios where speed outweighs reliability, such as real-time video streaming, online gaming, DNS queries, and local network discovery. However, this simplicity makes it exceptionally fast and

procedure TForm1.FormCreate(Sender: TObject); begin IdUDPServer1.DefaultPort := 8080; IdUDPServer1.Active := True; end; This unit provides a cleaner, non-blocking architecture and is ideal for FireMonkey (FMX) applications. Sending a UDP Datagram uses System.Net.Socket, System.Net.URLClient; procedure SendUDP(const AHost: string; APort: Integer; const AMessage: string); var Socket: TUdpSocket; RemoteEndpoint: TEndpoint; Bytes: TBytes; begin Socket := TUdpSocket.Create; try RemoteEndpoint := TEndpoint.Create(AHost, APort); Bytes := TEncoding.UTF8.GetBytes(AMessage); Socket.SendTo(RemoteEndpoint, Bytes, 0, Length(Bytes)); finally Socket.Free; end; end; Receiving UDP Datagrams (Async) type TUDPReceiver = class private FSocket: TUdpSocket; procedure OnDataAvailable(const AData: TBytes; AEndpoint: TEndpoint); public procedure StartListening(APort: Integer); end; procedure TUDPReceiver.StartListening(APort: Integer); begin FSocket := TUdpSocket.Create; FSocket.Listen(APort); // Bind to local port FSocket.ReceiveFrom(OnDataAvailable); // Non-blocking callback end;

For production code, consider using a higher-level abstraction or message queue, but for many real-time and discovery scenarios, UDP in Delphi is both efficient and elegant.