TsgcSSEClient

TsgcSSEClient is a Server-Sent Events (EventSource) client that receives a text/event-stream over HTTP and reconnects automatically.

Introduction

TsgcSSEClient connects to a URL that returns a text/event-stream, reads the stream on a background thread and fires an event for every message the server pushes. When the stream ends or the network fails, the client reconnects automatically and sends the Last-Event-ID header, so the server can resume the stream from the last event received. A retry: field sent by the server sets the reconnection delay for the rest of the session. The component is available in all editions and is registered in the SGC HTTP palette tab.

 

Follow the steps below to configure this component:

 

1. Create a new instance of TsgcSSEClient component and set the URL of the event stream.

 

2. Handle the OnEvent event and call Open. Example:

 


uses
  sgcHTTP_SSE_Client;

oSSE := TsgcSSEClient.Create(nil);
oSSE.URL := 'https://www.example.com/events';
oSSE.OnEvent := OnSSEEvent;
oSSE.Open;

procedure TForm1.OnSSEEvent(Sender: TObject; const aEvent: TsgcSSEEvent);
begin
  ShowMessage(aEvent.EventType + ': ' + aEvent.Data);
end;

 

How the client reacts to the server response:

 

ReconnectOptions.MaxAttempts counts consecutive failures, and the counter restarts every time a connection opens. Use Headers to add request headers such as a bearer token, and OnBeforeConnect to configure TLS, a proxy or authentication on the underlying TsgcHTTP1Client.

 

Reference

Guides