Sample code for 30+ languages & platforms
Pascal (Lazarus/Delphi)

Firebase Receive Server-Sent Events (text/event-stream)

See more Firebase Examples

Demonstrates how to start receiving server-sent events and update your JSON database with each event.

Chilkat Pascal (Lazarus/Delphi) Downloads

Pascal (Lazarus/Delphi)
program ChilkatDemo;

// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}

uses
  {$IFDEF UNIX}
  cthreads,
  {$ENDIF}
  SysUtils,
  CkDllLoader,
  Chilkat.AuthGoogle,
  Chilkat.Url,
  Chilkat.FileAccess,
  Chilkat.Stream,
  Chilkat.Rest,
  Chilkat.JsonObject,
  Chilkat.ServerSentEvent,
  Chilkat.Task;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  success: Boolean;
  fac: TFileAccess;
  accessToken: string;
  rest: TRest;
  authGoogle: TAuthGoogle;
  responseBody: string;
  urlStr: string;
  url: TUrl;
  rest2: TRest;
  responseStatusCode: Integer;
  jsonDb: TJsonObject;
  eventStream: TStream;
  sse: TServerSentEvent;
  task: TTask;
  count: Integer;
  eventStr: string;

begin
  success := False;

  //  Demonstrates how to begin receiving server-sent events, and to update
  //  your JSON database for each event.

  //  This example requires the Chilkat API to have been previously unlocked.
  //  See Global Unlock Sample for sample code.

  //  This example assumes a JWT authentication token, if required, has been previously obtained.
  //  See Get Firebase Access Token from JSON Service Account Private Key for sample code.

  //  Load the previously obtained Firebase access token into a string.
  fac := TFileAccess.Create;
  accessToken := fac.ReadEntireTextFile('qa_data/tokens/firebaseToken.txt','utf-8');
  if (fac.LastMethodSuccess = False) then
    begin
      WriteLn(fac.LastErrorText);
      Exit;
    end;

  rest := TRest.Create;

  //  Make the initial connection (without sending a request yet).
  //  Once connected, any number of requests may be sent.  It is not necessary to explicitly
  //  call Connect before each request.  
  success := rest.Connect('chilkat.firebaseio.com',443,True,True);
  if (success = False) then
    begin
      WriteLn(rest.LastErrorText);
      Exit;
    end;

  authGoogle := TAuthGoogle.Create;
  authGoogle.AccessToken := accessToken;
  rest.SetAuthGoogle(authGoogle);

  rest.AddHeader('Accept','text/event-stream');
  rest.AddHeader('Cache-Control','no-cache');

  responseBody := rest.FullRequestNoBody('GET','/.json');

  //  A 307 redirect response is expected.
  if (rest.ResponseStatusCode <> 307) then
    begin
      WriteLn('Unexpected response code: ' + rest.ResponseStatusCode);
      WriteLn(responseBody);
      WriteLn('Failed.');
      Exit;
    end;

  //  Get the redirect URL
  urlStr := rest.LastRedirectUrl;
  url := TUrl.Create;
  url.ParseUrl(urlStr);

  WriteLn('redirect URL domain: ' + url.Host);
  WriteLn('redirect URL path: ' + url.Path);
  WriteLn('redirect URL query params: ' + url.Query);
  WriteLn('redirect URL path with query params: ' + url.PathWithQueryParams);

  //  Our text/event-stream will be obtained from the redirect URL...
  rest2 := TRest.Create;

  success := rest2.Connect(url.Host,443,True,True);
  if (success <> True) then
    begin
      WriteLn(rest2.LastErrorText);
      Exit;
    end;

  rest2.AddHeader('Accept','text/event-stream');
  rest2.AddHeader('Cache-Control','no-cache');

  //  Add the redirect query params to the request
  rest2.AddQueryParams(url.Query);

  //  In our case, we don't actually need the auth query param,
  //  so remove it.
  rest2.RemoveQueryParam('auth');

  //  Send the request.  (We are only sending the request here.
  //  We are not yet getting the response because the response
  //  will be a text/event-stream.)
  success := rest2.SendReqNoBody('GET',url.Path);
  if (success <> True) then
    begin
      WriteLn(rest2.LastErrorText);
      Exit;
    end;

  //  Read the response header.  
  //  We want to first get the response header to see if it's a successful
  //  response status code.  If not, then the response will not be a text/event-stream
  //  and we should read the response body normally.
  responseStatusCode := rest2.ReadResponseHeader();
  if (responseStatusCode < 0) then
    begin
      WriteLn(rest2.LastErrorText);
      Exit;
    end;

  //  If successful, a 200 response code is expected.
  //  If the reponse code is not 200, then read the response body and fail..
  if (responseStatusCode <> 200) then
    begin
      WriteLn('Response Code: ' + responseStatusCode);
      WriteLn('Response Status Text: ' + rest2.ResponseStatusText);
      WriteLn('Response Header: ' + rest2.ResponseHeader);
      responseBody := rest2.ReadRespBodyString();
      if (rest2.LastMethodSuccess = True) then
        begin
          WriteLn('Error Response Body: ' + responseBody);
        end;
      WriteLn('Failed.');
      Exit;
    end;

  //  For this example, our JSON database will be empty at the beginning.
  //  The incoming events (put and patch) will be applied to this database.
  jsonDb := TJsonObject.Create;

  //  Make sure to set the JSON path delimiter to "/".  The default is "." and this
  //  is not compatible with Firebase paths.
  jsonDb.DelimiterChar := '/';

  //  At this point, we've received the response header.  Now it's time to begin
  //  receiving the event stream.  We'll start a background thread to read the 
  //  stream.  (Our main application (foreground) thread can cancel it at any time.)  
  //  While receiving in the background thread, our foreground thread can read the stream
  //  as it desires..
  eventStream := TStream.Create;

  //  This sse object will be used as a helper to parse the server-sent event stream.
  sse := TServerSentEvent.Create;

  task := rest2.ReadRespBodyStreamAsync(eventStream,True);
  task.Run();

  //  For this example, we'll just read a few events, and then cancel the
  //  async task.
  count := 0;
  while (count < 3) and (task.Finished = False) do
    begin

      //  Get the next event, which is a series of text lines ending with
      //  a blank line. 
      //  Note: This method blocks the calling thread until a message arrives.
      //  a program might instead periodically check the availability of
      //  data via the stream's DataAvailable property, and then do the read.

      //  An alternative to writing a while loop to read the event stream
      //  would be to setup some sort of timer event in your program (using whatever timer functionality
      //  is provided in a programming language/environment), to periodically check the eventStream's
      //  DataAvailable property and consume the incoming event.
      eventStr := eventStream.ReadUntilMatch(#13#10 + #13#10);
      if (eventStream.LastMethodSuccess <> True) then
        begin
          WriteLn(eventStream.LastErrorText);
          //  Force the loop to exit by setting the count to a high number.
          count := 99999;
        end
      else
        begin
          WriteLn('Event: [' + eventStr + ']');

          //  We have an event. Let's update our local copy of the JSON database.
          success := sse.LoadEvent(eventStr);
          if (success <> True) then
            begin
              WriteLn('Failed to load sse event: ' + eventStr);
            end
          else
            begin
              //  Now we can easily access the event name and data, and apply it to our JSON database:
              success := jsonDb.FirebaseApplyEvent(sse.EventName,sse.Data);
              if (success <> True) then
                begin
                  WriteLn('Failed to apply event: ' + sse.EventName + ': ' + sse.Data);
                end
              else
                begin
                  WriteLn('Successfully applied event: ' + sse.EventName + ': ' + sse.Data);
                end;
            end;
        end;
      count := count + 1;
    end;

  //  Make sure the background task is cancelled if still running.
  task.Cancel();

  task.Free;

  //  Examine the JSON database after applying events..
  jsonDb.EmitCompact := False;
  WriteLn('----');
  WriteLn(jsonDb.Emit());


  fac.Free;
  rest.Free;
  authGoogle.Free;
  url.Free;
  rest2.Free;
  jsonDb.Free;
  eventStream.Free;
  sse.Free;

end;

// ---------------------------------------------------------------------------

begin

  try
    RunDemo;
  except
    on E: Exception do
      WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
  end;

  WriteLn;
  {$IFDEF MSWINDOWS}
  WriteLn('Press Enter to exit...');
  ReadLn;
  {$ENDIF}
end.