Sample code for 30+ languages & platforms
PowerBuilder

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

PowerBuilder
integer li_rc
integer li_Success
oleobject loo_Fac
string ls_AccessToken
oleobject loo_Rest
oleobject loo_AuthGoogle
string ls_ResponseBody
string ls_UrlStr
oleobject loo_Url
oleobject loo_Rest2
integer li_ResponseStatusCode
oleobject loo_JsonDb
oleobject loo_EventStream
oleobject loo_Sse
oleobject loo_Task
integer li_Count
string ls_EventStr

li_Success = 0

// 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.
loo_Fac = create oleobject
li_rc = loo_Fac.ConnectToNewObject("Chilkat.FileAccess")
if li_rc < 0 then
    destroy loo_Fac
    MessageBox("Error","Connecting to COM object failed")
    return
end if
ls_AccessToken = loo_Fac.ReadEntireTextFile("qa_data/tokens/firebaseToken.txt","utf-8")
if loo_Fac.LastMethodSuccess = 0 then
    Write-Debug loo_Fac.LastErrorText
    destroy loo_Fac
    return
end if

loo_Rest = create oleobject
li_rc = loo_Rest.ConnectToNewObject("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.  
li_Success = loo_Rest.Connect("chilkat.firebaseio.com",443,1,1)
if li_Success = 0 then
    Write-Debug loo_Rest.LastErrorText
    destroy loo_Fac
    destroy loo_Rest
    return
end if

loo_AuthGoogle = create oleobject
li_rc = loo_AuthGoogle.ConnectToNewObject("Chilkat.AuthGoogle")

loo_AuthGoogle.AccessToken = ls_AccessToken
loo_Rest.SetAuthGoogle(loo_AuthGoogle)

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

ls_ResponseBody = loo_Rest.FullRequestNoBody("GET","/.json")

// A 307 redirect response is expected.
if loo_Rest.ResponseStatusCode <> 307 then
    Write-Debug "Unexpected response code: " + string(loo_Rest.ResponseStatusCode)
    Write-Debug ls_ResponseBody
    Write-Debug "Failed."
    destroy loo_Fac
    destroy loo_Rest
    destroy loo_AuthGoogle
    return
end if

// Get the redirect URL
ls_UrlStr = loo_Rest.LastRedirectUrl
loo_Url = create oleobject
li_rc = loo_Url.ConnectToNewObject("Chilkat.Url")

loo_Url.ParseUrl(ls_UrlStr)

Write-Debug "redirect URL domain: " + loo_Url.Host
Write-Debug "redirect URL path: " + loo_Url.Path
Write-Debug "redirect URL query params: " + loo_Url.Query
Write-Debug "redirect URL path with query params: " + loo_Url.PathWithQueryParams

// Our text/event-stream will be obtained from the redirect URL...
loo_Rest2 = create oleobject
li_rc = loo_Rest2.ConnectToNewObject("Chilkat.Rest")

li_Success = loo_Rest2.Connect(loo_Url.Host,443,1,1)
if li_Success <> 1 then
    Write-Debug loo_Rest2.LastErrorText
    destroy loo_Fac
    destroy loo_Rest
    destroy loo_AuthGoogle
    destroy loo_Url
    destroy loo_Rest2
    return
end if

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

// Add the redirect query params to the request
loo_Rest2.AddQueryParams(loo_Url.Query)

// In our case, we don't actually need the auth query param,
// so remove it.
loo_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.)
li_Success = loo_Rest2.SendReqNoBody("GET",loo_Url.Path)
if li_Success <> 1 then
    Write-Debug loo_Rest2.LastErrorText
    destroy loo_Fac
    destroy loo_Rest
    destroy loo_AuthGoogle
    destroy loo_Url
    destroy loo_Rest2
    return
end if

// 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.
li_ResponseStatusCode = loo_Rest2.ReadResponseHeader()
if li_ResponseStatusCode < 0 then
    Write-Debug loo_Rest2.LastErrorText
    destroy loo_Fac
    destroy loo_Rest
    destroy loo_AuthGoogle
    destroy loo_Url
    destroy loo_Rest2
    return
end if

// If successful, a 200 response code is expected.
// If the reponse code is not 200, then read the response body and fail..
if li_ResponseStatusCode <> 200 then
    Write-Debug "Response Code: " + string(li_ResponseStatusCode)
    Write-Debug "Response Status Text: " + loo_Rest2.ResponseStatusText
    Write-Debug "Response Header: " + loo_Rest2.ResponseHeader
    ls_ResponseBody = loo_Rest2.ReadRespBodyString()
    if loo_Rest2.LastMethodSuccess = 1 then
        Write-Debug "Error Response Body: " + ls_ResponseBody
    end if

    Write-Debug "Failed."
    destroy loo_Fac
    destroy loo_Rest
    destroy loo_AuthGoogle
    destroy loo_Url
    destroy loo_Rest2
    return
end if

// For this example, our JSON database will be empty at the beginning.
// The incoming events (put and patch) will be applied to this database.
loo_JsonDb = create oleobject
li_rc = loo_JsonDb.ConnectToNewObject("Chilkat.JsonObject")

// Make sure to set the JSON path delimiter to "/".  The default is "." and this
// is not compatible with Firebase paths.
loo_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..
loo_EventStream = create oleobject
li_rc = loo_EventStream.ConnectToNewObject("Chilkat.Stream")

// This sse object will be used as a helper to parse the server-sent event stream.
loo_Sse = create oleobject
li_rc = loo_Sse.ConnectToNewObject("Chilkat.ServerSentEvent")

loo_Task = loo_Rest2.ReadRespBodyStreamAsync(loo_EventStream,1)
loo_Task.Run()

// For this example, we'll just read a few events, and then cancel the
// async task.
li_Count = 0
do while (li_Count < 3) AND (loo_Task.Finished = 0)

    // 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.
    ls_EventStr = loo_EventStream.ReadUntilMatch("~r~n~r~n")
    if loo_EventStream.LastMethodSuccess <> 1 then
        Write-Debug loo_EventStream.LastErrorText
        // Force the loop to exit by setting the count to a high number.
        li_Count = 99999
    else
        Write-Debug "Event: [" + ls_EventStr + "]"

        // We have an event. Let's update our local copy of the JSON database.
        li_Success = loo_Sse.LoadEvent(ls_EventStr)
        if li_Success <> 1 then
            Write-Debug "Failed to load sse event: " + ls_EventStr
        else
            // Now we can easily access the event name and data, and apply it to our JSON database:
            li_Success = loo_JsonDb.FirebaseApplyEvent(loo_Sse.EventName,loo_Sse.Data)
            if li_Success <> 1 then
                Write-Debug "Failed to apply event: " + loo_Sse.EventName + ": " + loo_Sse.Data
            else
                Write-Debug "Successfully applied event: " + loo_Sse.EventName + ": " + loo_Sse.Data
            end if

        end if

    end if

    li_Count = li_Count + 1
loop

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

destroy loo_Task

// Examine the JSON database after applying events..
loo_JsonDb.EmitCompact = 0
Write-Debug "----"
Write-Debug loo_JsonDb.Emit()


destroy loo_Fac
destroy loo_Rest
destroy loo_AuthGoogle
destroy loo_Url
destroy loo_Rest2
destroy loo_JsonDb
destroy loo_EventStream
destroy loo_Sse