Chilkat Examples

ChilkatHOMEAndroid™Classic ASPCC++C#Mono C#.NET Core C#C# UWP/WinRTDataFlexDelphi ActiveXDelphi DLLVisual FoxProJavaLianjaMFCObjective-CPerlPHP ActiveXPHP ExtensionPowerBuilderPowerShellPureBasicPythonRubySQL ServerSwiftTclUnicode CUnicode C++Visual Basic 6.0VB.NETVB.NET UWP/WinRTVBScriptXojo PluginNode.jsExcel

PHP ActiveX Examples


ASN.1
Amazon S3
Amazon S3 (new)
Amazon SES
Amazon SNS
Amazon SQS
Async
Azure Cloud Storage
Azure Service Bus
Bounced Email
Box
CSR
CSV
Certificates
Compression
DKIM / DomainKey
DSA
Diffie-Hellman
Digital Signatures
Dropbox
ECC
Email Object
Encryption
FTP
Facebook
Firebase
GeoOp
Google APIs
Google Calendar
Google Cloud Storage
Google Drive
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
Microsoft Graph
NTLM
OAuth1
OAuth2
OneDrive
OpenSSL
Outlook
PEM
PFX/P12
POP3
PRNG
PayPal
Peoplevox
QuickBooks
REST
RSA Encryption
SCP
SFTP
SMTP
SSH
SSH Key
SSH Tunnel
SharePoint
Shopify
Socket/SSL/TLS
Spider
Stream
Stripe
SugarCRM
Tar Archive
Twitter
VoiceBase
Walmart
WebSocket
XML
XML Digital Signatures
XMP
Xero
Zip
curl
eBay

 

 

 

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

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

Important: A problem in reading the response text/event-stream was found and fixed after the release of Chilkat v9.5.0.69. This example is valid for Chilkat v9.5.0.70 and greater. (At the time of this writing, which is 18-Sep-2017, Chilkat v9.5.0.70 is not yet released. A .70 pre-release can be obtained by sending a request to support@chilkatsoft.com.)

Chilkat ActiveX Downloads

ActiveX for 32-bit and 64-bit Windows

<?php

//  ---------------------------------------------------------------------------------------------
//  Important: A problem in reading the response text/event-stream was found and fixed after the release of Chilkat v9.5.0.69.
//  This example is valid for Chilkat v9.5.0.70 and greater.
//  (At the time of this writing, which is 18-Sep-2017, Chilkat v9.5.0.70 is not yet released.
//  A .70 pre-release can be obtained by sending a request to support@chilkatsoft.com.)
//  ---------------------------------------------------------------------------------------------

//  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 = new COM("Chilkat_9_5_0.FileAccess");
$accessToken = $fac->readEntireTextFile('qa_data/tokens/firebaseToken.txt','utf-8');
if ($fac->LastMethodSuccess != 1) {
    print $fac->LastErrorText . "\n";
    exit;
}

$rest = new COM("Chilkat_9_5_0.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 != 1) {
    print $rest->LastErrorText . "\n";
    exit;
}

$authGoogle = new COM("Chilkat_9_5_0.AuthGoogle");
$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) {
    print 'Unexpected response code: ' . $rest->ResponseStatusCode . "\n";
    print $responseBody . "\n";
    print 'Failed.' . "\n";
    exit;
}

//  Get the redirect URL
// url is a Chilkat_9_5_0.Url
$url = $rest->RedirectUrl();
if ($rest->LastMethodSuccess != 1) {
    print $rest->LastErrorText . "\n";
    exit;
}

print 'redirect URL domain: ' . $url->Host . "\n";
print 'redirect URL path: ' . $url->Path . "\n";
print 'redirect URL query params: ' . $url->Query . "\n";
print 'redirect URL path with query params: ' . $url->PathWithQueryParams . "\n";

//  Our text/event-stream will be obtained from the redirect URL...
$rest2 = new COM("Chilkat_9_5_0.Rest");

$success = $rest2->Connect($url->Host,443,1,1);
if ($success != 1) {
    print $rest2->LastErrorText . "\n";

    exit;
}

$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 != 1) {
    print $rest2->LastErrorText . "\n";

    exit;
}

//  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) {
    print $rest2->LastErrorText . "\n";
    exit;
}

//  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) {
    print 'Response Code: ' . $responseStatusCode . "\n";
    print 'Response Status Text: ' . $rest2->ResponseStatusText . "\n";
    print 'Response Header: ' . $rest2->ResponseHeader . "\n";
    $responseBody = $rest2->readRespBodyString();
    if ($rest2->LastMethodSuccess == 1) {
        print 'Error Response Body: ' . $responseBody . "\n";
    }

    print 'Failed.' . "\n";
    exit;
}

//  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 = new COM("Chilkat_9_5_0.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..
$eventStream = new COM("Chilkat_9_5_0.Stream");

//  This sse object will be used as a helper to parse the server-sent event stream.
$sse = new COM("Chilkat_9_5_0.ServerSentEvent");

// task is a Chilkat_9_5_0.Task
$task = $rest2->ReadRespBodyStreamAsync($eventStream,1);
$task->Run();

//  For this example, we'll just read a few events, and then cancel the
//  async task.
$count = 0;
while (($count < 0) 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('\r\n\r\n');
    if ($eventStream->LastMethodSuccess != 1) {
        print $eventStream->LastErrorText . "\n";
        //  Force the loop to exit by setting the count to a high number.
        $count = 99999;
    }
    else {
        print 'Event: [' . $eventStr . ']' . "\n";

        //  We have an event. Let's update our local copy of the JSON database.
        $success = $sse->LoadEvent($eventStr);
        if ($success != 1) {
            print 'Failed to load sse event: ' . $eventStr . "\n";
        }
        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) {
                print 'Failed to apply event: ' . $sse->EventName . ': ' . $sse->Data . "\n";
            }
            else {
                print 'Successfully applied event: ' . $sse->EventName . ': ' . $sse->Data . "\n";
            }

        }

    }

    $count = $count + 1;
}

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

//  Examine the JSON database after applying events..
$jsonDb->EmitCompact = 0;
print '----' . "\n";
print $jsonDb->emit() . "\n";

?>

 

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