Chilkat Examples

ChilkatHOME.NET Core C#Android™AutoItCC#C++Chilkat2-PythonCkPythonClassic ASPDataFlexDelphi ActiveXDelphi DLLGoJavaLianjaMono C#Node.jsObjective-CPHP ActiveXPHP ExtensionPerlPowerBuilderPowerShellPureBasicRubySQL ServerSwift 2Swift 3,4,5...TclUnicode CUnicode C++VB.NETVBScriptVisual Basic 6.0Visual FoxProXojo Plugin

Visual FoxPro Examples

Web API Categories

ASN.1
AWS KMS
AWS Misc
Amazon EC2
Amazon Glacier
Amazon S3
Amazon S3 (new)
Amazon SES
Amazon SNS
Amazon SQS
Async
Azure Cloud Storage
Azure Key Vault
Azure Service Bus
Azure Table Service
Base64
Bounced Email
Box
CAdES
CSR
CSV
Certificates
Cloud Signature CSC
Code Signing
Compression
DKIM / DomainKey
DNS
DSA
Diffie-Hellman
Digital Signatures
Dropbox
Dynamics CRM
EBICS
ECC
Ed25519
Email Object
Encryption
FTP
FileAccess
Firebase
GMail REST API
GMail SMTP/IMAP/POP
Geolocation
Google APIs
Google Calendar
Google Cloud SQL
Google Cloud Storage
Google Drive
Google Photos
Google Sheets
Google Tasks
Gzip
HTML-to-XML/Text
HTTP

HTTP Misc
IMAP
JSON
JSON Web Encryption (JWE)
JSON Web Signatures (JWS)
JSON Web Token (JWT)
Java KeyStore (JKS)
MHT / HTML Email
MIME
MS Storage Providers
Microsoft Graph
Misc
NTLM
OAuth1
OAuth2
OIDC
Office365
OneDrive
OpenSSL
Outlook
Outlook Calendar
Outlook Contact
PDF Signatures
PEM
PFX/P12
PKCS11
POP3
PRNG
REST
REST Misc
RSA
SCP
SCard
SFTP
SMTP
SSH
SSH Key
SSH Tunnel
ScMinidriver
SharePoint
SharePoint Online
Signing in the Cloud
Socket/SSL/TLS
Spider
Stream
Tar Archive
ULID/UUID
Upload
WebSocket
XAdES
XML
XML Digital Signatures
XMP
Zip
curl
uncategorized

 

 

 

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

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

Chilkat ActiveX Downloads

ActiveX for 32-bit and 64-bit Windows

LOCAL loFac
LOCAL lcAccessToken
LOCAL loRest
LOCAL lnSuccess
LOCAL loAuthGoogle
LOCAL lcResponseBody
LOCAL loUrl
LOCAL loRest2
LOCAL lnResponseStatusCode
LOCAL loJsonDb
LOCAL loEventStream
LOCAL loSse
LOCAL loTask
LOCAL lnCount
LOCAL lcEventStr

* 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.
* For versions of Chilkat < 10.0.0, use CreateObject('Chilkat_9_5_0.FileAccess')
loFac = CreateObject('Chilkat.FileAccess')
lcAccessToken = loFac.ReadEntireTextFile("qa_data/tokens/firebaseToken.txt","utf-8")
IF (loFac.LastMethodSuccess <> 1) THEN
    ? loFac.LastErrorText
    RELEASE loFac
    CANCEL
ENDIF

* For versions of Chilkat < 10.0.0, use CreateObject('Chilkat_9_5_0.Rest')
loRest = 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.  
lnSuccess = loRest.Connect("chilkat.firebaseio.com",443,1,1)
IF (lnSuccess <> 1) THEN
    ? loRest.LastErrorText
    RELEASE loFac
    RELEASE loRest
    CANCEL
ENDIF

* For versions of Chilkat < 10.0.0, use CreateObject('Chilkat_9_5_0.AuthGoogle')
loAuthGoogle = CreateObject('Chilkat.AuthGoogle')
loAuthGoogle.AccessToken = lcAccessToken
loRest.SetAuthGoogle(loAuthGoogle)

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

lcResponseBody = loRest.FullRequestNoBody("GET","/.json")

* A 307 redirect response is expected.
IF (loRest.ResponseStatusCode <> 307) THEN
    ? "Unexpected response code: " + STR(loRest.ResponseStatusCode)
    ? lcResponseBody
    ? "Failed."
    RELEASE loFac
    RELEASE loRest
    RELEASE loAuthGoogle
    CANCEL
ENDIF

* Get the redirect URL
loUrl = loRest.RedirectUrl()
IF (loRest.LastMethodSuccess <> 1) THEN
    ? loRest.LastErrorText
    RELEASE loFac
    RELEASE loRest
    RELEASE loAuthGoogle
    CANCEL
ENDIF

? "redirect URL domain: " + loUrl.Host
? "redirect URL path: " + loUrl.Path
? "redirect URL query params: " + loUrl.Query
? "redirect URL path with query params: " + loUrl.PathWithQueryParams

* Our text/event-stream will be obtained from the redirect URL...
* For versions of Chilkat < 10.0.0, use CreateObject('Chilkat_9_5_0.Rest')
loRest2 = CreateObject('Chilkat.Rest')

lnSuccess = loRest2.Connect(loUrl.Host,443,1,1)
IF (lnSuccess <> 1) THEN
    ? loRest2.LastErrorText
    RELEASE loUrl
    RELEASE loFac
    RELEASE loRest
    RELEASE loAuthGoogle
    RELEASE loRest2
    CANCEL
ENDIF

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

* Add the redirect query params to the request
loRest2.AddQueryParams(loUrl.Query)

* In our case, we don't actually need the auth query param,
* so remove it.
loRest2.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.)
lnSuccess = loRest2.SendReqNoBody("GET",loUrl.Path)
IF (lnSuccess <> 1) THEN
    ? loRest2.LastErrorText
    RELEASE loUrl
    RELEASE loFac
    RELEASE loRest
    RELEASE loAuthGoogle
    RELEASE loRest2
    CANCEL
ENDIF

RELEASE loUrl

* 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.
lnResponseStatusCode = loRest2.ReadResponseHeader()
IF (lnResponseStatusCode < 0) THEN
    ? loRest2.LastErrorText
    RELEASE loFac
    RELEASE loRest
    RELEASE loAuthGoogle
    RELEASE loRest2
    CANCEL
ENDIF

* If successful, a 200 response code is expected.
* If the reponse code is not 200, then read the response body and fail..
IF (lnResponseStatusCode <> 200) THEN
    ? "Response Code: " + STR(lnResponseStatusCode)
    ? "Response Status Text: " + loRest2.ResponseStatusText
    ? "Response Header: " + loRest2.ResponseHeader
    lcResponseBody = loRest2.ReadRespBodyString()
    IF (loRest2.LastMethodSuccess = 1) THEN
        ? "Error Response Body: " + lcResponseBody
    ENDIF

    ? "Failed."
    RELEASE loFac
    RELEASE loRest
    RELEASE loAuthGoogle
    RELEASE loRest2
    CANCEL
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.
* For versions of Chilkat < 10.0.0, use CreateObject('Chilkat_9_5_0.JsonObject')
loJsonDb = CreateObject('Chilkat.JsonObject')

* Make sure to set the JSON path delimiter to "/".  The default is "." and this
* is not compatible with Firebase paths.
loJsonDb.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..
* For versions of Chilkat < 10.0.0, use CreateObject('Chilkat_9_5_0.Stream')
loEventStream = CreateObject('Chilkat.Stream')

* This sse object will be used as a helper to parse the server-sent event stream.
* For versions of Chilkat < 10.0.0, use CreateObject('Chilkat_9_5_0.ServerSentEvent')
loSse = CreateObject('Chilkat.ServerSentEvent')

loTask = loRest2.ReadRespBodyStreamAsync(loEventStream,1)
loTask.Run()

* For this example, we'll just read a few events, and then cancel the
* async task.
lnCount = 0
DO WHILE (lnCount < 3) AND (loTask.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.
    lcEventStr = loEventStream.ReadUntilMatch(CHR(13) + CHR(10) + CHR(13) + CHR(10))
    IF (loEventStream.LastMethodSuccess <> 1) THEN
        ? loEventStream.LastErrorText
        * Force the loop to exit by setting the count to a high number.
        lnCount = 99999
    ELSE
        ? "Event: [" + lcEventStr + "]"

        * We have an event. Let's update our local copy of the JSON database.
        lnSuccess = loSse.LoadEvent(lcEventStr)
        IF (lnSuccess <> 1) THEN
            ? "Failed to load sse event: " + lcEventStr
        ELSE
            * Now we can easily access the event name and data, and apply it to our JSON database:
            lnSuccess = loJsonDb.FirebaseApplyEvent(loSse.EventName,loSse.Data)
            IF (lnSuccess <> 1) THEN
                ? "Failed to apply event: " + loSse.EventName + ": " + loSse.Data
            ELSE
                ? "Successfully applied event: " + loSse.EventName + ": " + loSse.Data
            ENDIF

        ENDIF

    ENDIF

    lnCount = lnCount + 1
ENDDO

* Make sure the background task is cancelled if still running.
loTask.Cancel()

RELEASE loTask

* Examine the JSON database after applying events..
loJsonDb.EmitCompact = 0
? "----"
? loJsonDb.Emit()

RELEASE loFac
RELEASE loRest
RELEASE loAuthGoogle
RELEASE loRest2
RELEASE loJsonDb
RELEASE loEventStream
RELEASE loSse


 

© 2000-2024 Chilkat Software, Inc. All Rights Reserved.