Sample code for 30+ languages & platforms
Classic ASP

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 Classic ASP Downloads

Classic ASP
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<%
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.
set fac = Server.CreateObject("Chilkat.FileAccess")
accessToken = fac.ReadEntireTextFile("qa_data/tokens/firebaseToken.txt","utf-8")
If (fac.LastMethodSuccess = 0) Then
    Response.Write "<pre>" & Server.HTMLEncode( fac.LastErrorText) & "</pre>"
    Response.End
End If

set rest = Server.CreateObject("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.  
success = rest.Connect("chilkat.firebaseio.com",443,1,1)
If (success = 0) Then
    Response.Write "<pre>" & Server.HTMLEncode( rest.LastErrorText) & "</pre>"
    Response.End
End If

set authGoogle = Server.CreateObject("Chilkat.AuthGoogle")
authGoogle.AccessToken = accessToken
success = rest.SetAuthGoogle(authGoogle)

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

responseBody = rest.FullRequestNoBody("GET","/.json")

' A 307 redirect response is expected.
If (rest.ResponseStatusCode <> 307) Then
    Response.Write "<pre>" & Server.HTMLEncode( "Unexpected response code: " & rest.ResponseStatusCode) & "</pre>"
    Response.Write "<pre>" & Server.HTMLEncode( responseBody) & "</pre>"
    Response.Write "<pre>" & Server.HTMLEncode( "Failed.") & "</pre>"
    Response.End
End If

' Get the redirect URL
urlStr = rest.LastRedirectUrl
set url = Server.CreateObject("Chilkat.Url")
success = url.ParseUrl(urlStr)

Response.Write "<pre>" & Server.HTMLEncode( "redirect URL domain: " & url.Host) & "</pre>"
Response.Write "<pre>" & Server.HTMLEncode( "redirect URL path: " & url.Path) & "</pre>"
Response.Write "<pre>" & Server.HTMLEncode( "redirect URL query params: " & url.Query) & "</pre>"
Response.Write "<pre>" & Server.HTMLEncode( "redirect URL path with query params: " & url.PathWithQueryParams) & "</pre>"

' Our text/event-stream will be obtained from the redirect URL...
set rest2 = Server.CreateObject("Chilkat.Rest")

success = rest2.Connect(url.Host,443,1,1)
If (success <> 1) Then
    Response.Write "<pre>" & Server.HTMLEncode( rest2.LastErrorText) & "</pre>"
    Response.End
End If

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

' Add the redirect query params to the request
success = rest2.AddQueryParams(url.Query)

' In our case, we don't actually need the auth query param,
' so remove it.
success = 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 <> 1) Then
    Response.Write "<pre>" & Server.HTMLEncode( rest2.LastErrorText) & "</pre>"
    Response.End
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.
responseStatusCode = rest2.ReadResponseHeader()
If (responseStatusCode < 0) Then
    Response.Write "<pre>" & Server.HTMLEncode( rest2.LastErrorText) & "</pre>"
    Response.End
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 (responseStatusCode <> 200) Then
    Response.Write "<pre>" & Server.HTMLEncode( "Response Code: " & responseStatusCode) & "</pre>"
    Response.Write "<pre>" & Server.HTMLEncode( "Response Status Text: " & rest2.ResponseStatusText) & "</pre>"
    Response.Write "<pre>" & Server.HTMLEncode( "Response Header: " & rest2.ResponseHeader) & "</pre>"
    responseBody = rest2.ReadRespBodyString()
    If (rest2.LastMethodSuccess = 1) Then
        Response.Write "<pre>" & Server.HTMLEncode( "Error Response Body: " & responseBody) & "</pre>"
    End If

    Response.Write "<pre>" & Server.HTMLEncode( "Failed.") & "</pre>"
    Response.End
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.
set jsonDb = Server.CreateObject("Chilkat.JsonObject")

' 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..
set eventStream = Server.CreateObject("Chilkat.Stream")

' This sse object will be used as a helper to parse the server-sent event stream.
set sse = Server.CreateObject("Chilkat.ServerSentEvent")

' task is a Chilkat.Task
Set task = rest2.ReadRespBodyStreamAsync(eventStream,1)
success = task.Run()

' For this example, we'll just read a few events, and then cancel the
' async task.
count = 0
Do While (count < 3) And (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.
    eventStr = eventStream.ReadUntilMatch(vbCrLf & vbCrLf)
    If (eventStream.LastMethodSuccess <> 1) Then
        Response.Write "<pre>" & Server.HTMLEncode( eventStream.LastErrorText) & "</pre>"
        ' Force the loop to exit by setting the count to a high number.
        count = 99999
    Else
        Response.Write "<pre>" & Server.HTMLEncode( "Event: [" & eventStr & "]") & "</pre>"

        ' We have an event. Let's update our local copy of the JSON database.
        success = sse.LoadEvent(eventStr)
        If (success <> 1) Then
            Response.Write "<pre>" & Server.HTMLEncode( "Failed to load sse event: " & eventStr) & "</pre>"
        Else
            ' 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 <> 1) Then
                Response.Write "<pre>" & Server.HTMLEncode( "Failed to apply event: " & sse.EventName & ": " & sse.Data) & "</pre>"
            Else
                Response.Write "<pre>" & Server.HTMLEncode( "Successfully applied event: " & sse.EventName & ": " & sse.Data) & "</pre>"
            End If

        End If

    End If

    count = count + 1
Loop

' Make sure the background task is cancelled if still running.
success = task.Cancel()

' Examine the JSON database after applying events..
jsonDb.EmitCompact = 0
Response.Write "<pre>" & Server.HTMLEncode( "----") & "</pre>"
Response.Write "<pre>" & Server.HTMLEncode( jsonDb.Emit()) & "</pre>"

%>
</body>
</html>