Chilkat Examples

ChilkatHOMEAndroid™Classic ASPCC++C#Mono C#.NET Core C#C# UWP/WinRTDataFlexDelphi ActiveXDelphi DLLVisual FoxProJavaLianjaMFCObjective-CPerlPHP ActiveXPHP ExtensionPowerBuilderPowerShellPureBasicCkPythonChilkat2-PythonRubySQL ServerSwift 2Swift 3,4,5...TclUnicode CUnicode C++Visual Basic 6.0VB.NETVB.NET UWP/WinRTVBScriptXojo PluginNode.jsExcelGo

DataFlex Examples

Web API Categories

ASN.1
Amazon EC2
Amazon Glacier
Amazon S3
Amazon S3 (new)
Amazon SES
Amazon SNS
Amazon SQS
Async
Azure Cloud Storage
Azure Service Bus
Azure Table Service
Base64
Bounced Email
Box
CAdES
CSR
CSV
Certificates
Compression
DKIM / DomainKey
DSA
Diffie-Hellman
Digital Signatures
Dropbox
Dynamics CRM
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
NTLM
OAuth1
OAuth2
Office365
OneDrive
OpenSSL
Outlook
Outlook Calendar
PDF Signatures
PEM
PFX/P12
POP3
PRNG
REST
REST Misc
RSA
SCP
SCard
SFTP
SMTP
SSH
SSH Key
SSH Tunnel
ScMinidriver
SharePoint
Socket/SSL/TLS
Spider
Stream
Tar Archive
Upload
WebSocket
XAdES
XML
XML Digital Signatures
XMP
Zip
curl

 

 

 

(DataFlex) Socket Select for Reading

Demonstrates how the Chilkat socket object can become a "socket set" that contains other connected socket objects, and this can be used to "select" on multiple sockets for reading. The SelectForReading method waits until one or more sockets in the set have incoming data ready and available to read.

Chilkat ActiveX Downloads

ActiveX for 32-bit and 64-bit Windows

Use ChilkatAx-9.5.0-win32.pkg

Procedure Test
    Variant vSock
etSet    Handle hoSocketSet
    Boolean iSuccess
    Handle hoSaDomains
    Handle hoSaUrls
    Handle hoSaFilenames
    Integer iNumConnections
    Integer i
    Boolean iUseSsl
    Integer iMaxWaitMs
    Integer iPort
    String sDomain
    String sGetReq
    Variant vSock
    Handle hoSock
    Integer iNumReady
    String sTemp1
    String sTemp2
    Boolean bTemp1

    // This example requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    // This will be the socket object that will contain other 
    // connected sockets.
    Get Create (RefClass(cComChilkatSocket)) To hoSocketSet
    If (Not(IsComObjectCreated(hoSocketSet))) Begin
        Send CreateComObject of hoSocketSet
    End

    // Before we begin, create a few StringArray objects holding
    // domain names, URLs, and output filenames to be used
    // in this example.
    Get Create (RefClass(cComCkStringArray)) To hoSaDomains
    If (Not(IsComObjectCreated(hoSaDomains))) Begin
        Send CreateComObject of hoSaDomains
    End
    Get Create (RefClass(cComCkStringArray)) To hoSaUrls
    If (Not(IsComObjectCreated(hoSaUrls))) Begin
        Send CreateComObject of hoSaUrls
    End
    Get Create (RefClass(cComCkStringArray)) To hoSaFilenames
    If (Not(IsComObjectCreated(hoSaFilenames))) Begin
        Send CreateComObject of hoSaFilenames
    End

    Get ComAppend Of hoSaDomains "www.chilkatsoft.com" To iSuccess
    Get ComAppend Of hoSaDomains "www.cknotes.com" To iSuccess
    Get ComAppend Of hoSaDomains "www.google.com" To iSuccess
    Get ComAppend Of hoSaDomains "www.example-code.com" To iSuccess
    Get ComAppend Of hoSaDomains "www.yahoo.com" To iSuccess

    Get ComAppend Of hoSaUrls "http://www.chilkatsoft.com/" To iSuccess
    Get ComAppend Of hoSaUrls "http://www.cknotes.com/" To iSuccess
    Get ComAppend Of hoSaUrls "http://www.google.com/" To iSuccess
    Get ComAppend Of hoSaUrls "http://www.example-code.com/" To iSuccess
    Get ComAppend Of hoSaUrls "http://www.yahoo.com/" To iSuccess

    Get ComAppend Of hoSaFilenames "chilkatsoft.out" To iSuccess
    Get ComAppend Of hoSaFilenames "cknotes.out" To iSuccess
    Get ComAppend Of hoSaFilenames "google.out" To iSuccess
    Get ComAppend Of hoSaFilenames "example-code.out" To iSuccess
    Get ComAppend Of hoSaFilenames "yahoo.out" To iSuccess

    Move 5 To iNumConnections

    // This example will connect to 5 different web servers,
    // send an HTTP request to each, and read the HTTP response
    // form each.  It will call the SelectForReading method to wait
    // until data arrives from any of the connected sockets.

    // NOTE: As you'll see later, communicating with HTTP servers
    // is better left to the Chilkat HTTP component/library because
    // of many HTTP protocol issues such as redirects, GZIP responses,
    // chunked responses, etc.  We're only communicating with
    // HTTP servers here as a convenient way of demonstrating
    // the technique of waiting for data to arrive from a set of 
    // connected sockets.

    // First, connect to each of the web servers:

    Move False To iUseSsl
    Move 5000 To iMaxWaitMs
    Move 80 To iPort

    For i From 0 To (iNumConnections - 1)
        Get Create (RefClass(cComChilkatSocket)) To hoSock
        If (Not(IsComObjectCreated(hoSock))) Begin
            Send CreateComObject of hoSock
        End

        Get ComGetString Of hoSaDomains i To sDomain

        Get ComConnect Of hoSock sDomain iPort iUseSsl iMaxWaitMs To iSuccess
        If (iSuccess <> True) Begin
            Get ComLastErrorText Of hoSock To sTemp1
            Showln sTemp1
            Procedure_Return
        End

        // Save a filename in the socket object's UserData.  We'll use this
        // later when saving the data read in the HTTP response.
        Get ComGetString Of hoSaFilenames i To sTemp1
        Set ComUserData Of hoSock To sTemp1

        // Display the remote IP address of the connected socket:
        Get ComRemoteIpAddress Of hoSock To sTemp1
        Showln "connected to " sTemp1

        // Build the HTTP GET request to be sent to the web server.
        Get ComGetString Of hoSaUrls i To sTemp1
        Get ComBuildHttpGetRequest Of hoSock sTemp1 To sGetReq

        // Send the HTTP GET request to the web server.
        Get ComSendString Of hoSock sGetReq To iSuccess
        If (iSuccess <> True) Begin
            Get ComLastErrorText Of hoSock To sTemp1
            Showln sTemp1
            Procedure_Return
        End

        // Tell the socketSet object to take ownership of the connected socket.
        // This adds the connection to the internal set of sockets contained
        // within socketSet.   
        Get pvComObject of hoSock to vSock
        Get ComTakeSocket Of hoSocketSet vSock To iSuccess
        If (iSuccess <> True) Begin
            // The TakeSocket method shouldn't fail.  The only reason it might
            // is if we try to give it an unconnected socket -- but we already 
            // know it's connected at this point..
            Get ComLastErrorText Of hoSocketSet To sTemp1
            Showln sTemp1
            Procedure_Return
        End

    Loop

    // At this point we have 5 TCP/IP connections contained within the socketSet object.
    // Each of the web servers have received a GET request and will be
    // sending a response.  We now want to write a loop that waits for data
    // to arrive from any of the 5 connections, reads incoming data, and
    // saves the data to files.

    // We'll use the StartTiming method and ElapsedSeconds property
    // to wait a maximum of 10 seconds.  The reason we do this is because
    // different web servers will behave differently w.r.t. idle connections.
    // Some web servers close the connections quickly while others do not.
    // The socket component is not "HTTP aware", meaning that it is not parsing
    // the HTTP response and therefore does not know when it has received
    // the full response.  Because of this, we might receive the full response
    // and then wait a long time before the server decides to close its side of
    // the connection.  
    // The ElapsedSeconds property will return the number of seconds that
    // have elapsed since the last call to StartTiming (on the same object instance).
    Send ComStartTiming To hoSocketSet

    While (((ComNumSocketsInSet(hoSocketSet)) > 0) And ((ComElapsedSeconds(hoSocketSet)) < 10))

        Move 300 To iMaxWaitMs

        // Wait for data to arrive on any of the sockets.  Waits a maximum
        // of 300 milliseconds.  If maxWaitMs = 0, then it is effectively a poll.
        // If no sockets have data available for reading, then a value of 0 is 
        // returned.  A value of -1 indicates an error condition.
        // Note: when the remote peer (in this case the web server) disconnects,
        // the socket will appear as if it has data available.  A "ready" socket
        // is one where either data is available for reading or the socket has
        // become disconnected.
        Get ComSelectForReading Of hoSocketSet iMaxWaitMs To iNumReady
        If (iNumReady < 0) Begin
            Get ComLastErrorText Of hoSocketSet To sTemp1
            Showln sTemp1
            Procedure_Return
        End

        // Consume data from each of the ready sockets, and show those
        // that become disconnected.   
        For i From 0 To (iNumReady - 1)

            // To make method calls on the "ready" socket, or to get/set property
            // values, set the SelectorReadIndex.  
            Set ComSelectorReadIndex Of hoSocketSet To i

            // Print information that identifies the socket that is ready for reading:
            Get ComRemoteIpAddress Of hoSocketSet To sTemp1
            Get ComUserData Of hoSocketSet To sTemp2
            Showln "ready: IP address = " sTemp1 " filename = " sTemp2

            // Read the selected socket and send the data directly to a file (appending
            // to the file).
            Get ComUserData Of hoSocketSet To sTemp1
            Get ComReceiveBytesToFile Of hoSocketSet sTemp1 To iSuccess

            // The success/failure of a socket read should normally be checked.
            // In this case it is not necessary.  If the socket became ready for
            // reading because the remote peer disconnected and there is no
            // data available, then nothing will be read.  The socketSet object
            // will automatically remove a disconnected socket from its internal set of sockets
            // the next time SelectForReading or SelectForWriting is called.
            // We can check to see if the socket is still connected by examining
            // the IsConnected property:
            Get ComIsConnected Of hoSocketSet To bTemp1
            If (bTemp1 <> True) Begin
                Get ComUserData Of hoSocketSet To sTemp1
                Showln "disconnected: " sTemp1
            End

        Loop

        // Set the SelectorReadIndex = -1 so that method calls
        // and property gets/sets are not routed to one of the socketSet's
        // contained sockets.  This is necessary because we want to
        // check the number of elapsed seconds from when we called
        // StartTiming.  
        Set ComSelectorReadIndex Of hoSocketSet To -1

    Loop

    Showln "Finished."

    // Some final notes:
    // If you examine the output files, you'll see that the HTTP protocol is a little
    // more complex than you may have originally thought.
    // 1) HTTP responses are MIME -- there is a MIME header followed by a MIME body.
    //     In most cases, the MIME body is the HTML document itself.
    // 2) Some HTTP responses return gzip compressed data (which is binary).  It must
    //      be decompressed to get the HTML.
    // 3) Some HTTP responses arrive in "chunked" form.  You'll see lines containing nothing but
    //      a hexidecimal number indicating the size of the chunk to follow.  It ends with
    //      a 0-sized chunk.
    // 4) You'll find that some HTTP responses might be redirects to other URL's (such as a 302 redirect).

    // For the above reasons, and many more, you would typically use the Chilkat HTTP component
    // to handle the complexities of HTTP.  

    // The reason HTTP was chosen for this example is because:
    // 1) It is easy to establish multiple connections with existing servers that are not typically not blocked by firewalls.
    // 2) It is easy to send a request and receive a response.
    // 3) There is variability  in the amount of time before a server decides to disconnect from an idle client


End_Procedure

 

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