Sample code for 30+ languages & platforms
AutoIt Requires Chilkat v11.0.0+

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 AutoIt Downloads

AutoIt
Local $bSuccess = 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.
$oFac = ObjCreate("Chilkat.FileAccess")
Local $sAccessToken = $oFac.ReadEntireTextFile("qa_data/tokens/firebaseToken.txt","utf-8")
If ($oFac.LastMethodSuccess = False) Then
    ConsoleWrite($oFac.LastErrorText & @CRLF)
    Exit
EndIf

$oRest = ObjCreate("Chilkat.Rest")

;  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.  
$bSuccess = $oRest.Connect("chilkat.firebaseio.com",443,True,True)
If ($bSuccess = False) Then
    ConsoleWrite($oRest.LastErrorText & @CRLF)
    Exit
EndIf

$oAuthGoogle = ObjCreate("Chilkat.AuthGoogle")
$oAuthGoogle.AccessToken = $sAccessToken
$oRest.SetAuthGoogle($oAuthGoogle)

$oRest.AddHeader("Accept","text/event-stream")
$oRest.AddHeader("Cache-Control","no-cache")

Local $sResponseBody = $oRest.FullRequestNoBody("GET","/.json")

;  A 307 redirect response is expected.
If ($oRest.ResponseStatusCode <> 307) Then
    ConsoleWrite("Unexpected response code: " & $oRest.ResponseStatusCode & @CRLF)
    ConsoleWrite($sResponseBody & @CRLF)
    ConsoleWrite("Failed." & @CRLF)
    Exit
EndIf

;  Get the redirect URL
Local $sUrlStr = $oRest.LastRedirectUrl
$oUrl = ObjCreate("Chilkat.Url")
$oUrl.ParseUrl($sUrlStr)

ConsoleWrite("redirect URL domain: " & $oUrl.Host & @CRLF)
ConsoleWrite("redirect URL path: " & $oUrl.Path & @CRLF)
ConsoleWrite("redirect URL query params: " & $oUrl.Query & @CRLF)
ConsoleWrite("redirect URL path with query params: " & $oUrl.PathWithQueryParams & @CRLF)

;  Our text/event-stream will be obtained from the redirect URL...
$oRest2 = ObjCreate("Chilkat.Rest")

$bSuccess = $oRest2.Connect($oUrl.Host,443,True,True)
If ($bSuccess <> True) Then
    ConsoleWrite($oRest2.LastErrorText & @CRLF)
    Exit
EndIf

$oRest2.AddHeader("Accept","text/event-stream")
$oRest2.AddHeader("Cache-Control","no-cache")

;  Add the redirect query params to the request
$oRest2.AddQueryParams($oUrl.Query)

;  In our case, we don't actually need the auth query param,
;  so remove it.
$oRest2.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.)
$bSuccess = $oRest2.SendReqNoBody("GET",$oUrl.Path)
If ($bSuccess <> True) Then
    ConsoleWrite($oRest2.LastErrorText & @CRLF)
    Exit
EndIf

;  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.
Local $iResponseStatusCode = $oRest2.ReadResponseHeader()
If ($iResponseStatusCode < 0) Then
    ConsoleWrite($oRest2.LastErrorText & @CRLF)
    Exit
EndIf

;  If successful, a 200 response code is expected.
;  If the reponse code is not 200, then read the response body and fail..
If ($iResponseStatusCode <> 200) Then
    ConsoleWrite("Response Code: " & $iResponseStatusCode & @CRLF)
    ConsoleWrite("Response Status Text: " & $oRest2.ResponseStatusText & @CRLF)
    ConsoleWrite("Response Header: " & $oRest2.ResponseHeader & @CRLF)
    $sResponseBody = $oRest2.ReadRespBodyString()
    If ($oRest2.LastMethodSuccess = True) Then
        ConsoleWrite("Error Response Body: " & $sResponseBody & @CRLF)
    EndIf

    ConsoleWrite("Failed." & @CRLF)
    Exit
EndIf

;  For this example, our JSON database will be empty at the beginning.
;  The incoming events (put and patch) will be applied to this database.
$oJsonDb = ObjCreate("Chilkat.JsonObject")

;  Make sure to set the JSON path delimiter to "/".  The default is "." and this
;  is not compatible with Firebase paths.
$oJsonDb.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..
$oEventStream = ObjCreate("Chilkat.Stream")

;  This sse object will be used as a helper to parse the server-sent event stream.
$oSse = ObjCreate("Chilkat.ServerSentEvent")

Local $oTask = $oRest2.ReadRespBodyStreamAsync($oEventStream,True)
$oTask.Run()

;  For this example, we'll just read a few events, and then cancel the
;  async task.
Local $iCount = 0
While ($iCount < 3) And ($oTask.Finished = False)

    ;  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.
Local $sEventStr = $oEventStream.ReadUntilMatch(@CRLF & @CRLF)
    If ($oEventStream.LastMethodSuccess <> True) Then
        ConsoleWrite($oEventStream.LastErrorText & @CRLF)
        ;  Force the loop to exit by setting the count to a high number.
        $iCount = 99999
    Else
        ConsoleWrite("Event: [" & $sEventStr & "]" & @CRLF)

        ;  We have an event. Let's update our local copy of the JSON database.
        $bSuccess = $oSse.LoadEvent($sEventStr)
        If ($bSuccess <> True) Then
            ConsoleWrite("Failed to load sse event: " & $sEventStr & @CRLF)
        Else
            ;  Now we can easily access the event name and data, and apply it to our JSON database:
            $bSuccess = $oJsonDb.FirebaseApplyEvent($oSse.EventName,$oSse.Data)
            If ($bSuccess <> True) Then
                ConsoleWrite("Failed to apply event: " & $oSse.EventName & ": " & $oSse.Data & @CRLF)
            Else
                ConsoleWrite("Successfully applied event: " & $oSse.EventName & ": " & $oSse.Data & @CRLF)
            EndIf

        EndIf

    EndIf

    $iCount = $iCount + 1
Wend

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

;  Examine the JSON database after applying events..
$oJsonDb.EmitCompact = False
ConsoleWrite("----" & @CRLF)
ConsoleWrite($oJsonDb.Emit() & @CRLF)