TsgcUDPServerEvents › OnUDPRead

OnUDPRead Event

Fires once per incoming UDP datagram, exposing the raw payload and the sender's IP/port.

Syntax

property OnUDPRead: TsgcUDPReadEvent;
// TsgcUDPReadEvent = procedure(Sender: TObject; Socket: TsgcUDPSocket; Bytes: TsgcBytes) of object

Default Value

Remarks

Fired once per received datagram, passing the raw bytes through the Bytes parameter and a Socket instance that carries both the peer endpoint (PeerIP, PeerPort) and the local binding (LocalIP, LocalPort) the datagram arrived on. UDP is connectionless, so every datagram may come from a different peer; keep the reply on the same conversation by calling WriteData with Socket.PeerIP and Socket.PeerPort. The payload is always delivered as bytes; convert it with TEncoding if the application protocol uses text. The thread that fires this event depends on NotifyEvents (default neNoSync). When DTLS is enabled, Bytes contains the decrypted plaintext for that peer.

Example

procedure TForm1.oServerUDPRead(Sender: TObject; Socket: TsgcUDPSocket;
  Bytes: TsgcBytes);
begin
  Memo1.Lines.Add(Format('From %s:%d -> %s',
    [Socket.PeerIP, Socket.PeerPort, TEncoding.UTF8.GetString(Bytes)]));
  oServer.WriteData(Socket.PeerIP, Socket.PeerPort, 'ack');
end;

Back to Events