Sample code for 30+ languages & platforms
PureBasic

Receive an Exact Number of Bytes into a BinData

See more Socket/SSL/TLS Examples

Demonstrates Socket.ReceiveBdN, which receives exactly the requested number of bytes and appends them to a BinData, continuing until the full count is satisfied.

Background. Inactivity is controlled by MaxReadIdleMs: the call fails if incoming bytes halt for longer than MaxReadIdleMs milliseconds before the full amount is received. A single receive returns only what is currently available, whereas this counted receive waits for an exact number of bytes.

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkBinData.pb"
IncludeFile "CkSocket.pb"

Procedure ChilkatExample()

    success.i = 0

    socket.i = CkSocket::ckCreate()
    If socket.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    ;  Connect to the server using TLS.
    bTls.i = 1
    maxWaitMs.i = 5000
    success = CkSocket::ckConnect(socket,"example.com",5000,bTls,maxWaitMs)
    If success = 0
        Debug CkSocket::ckLastErrorText(socket)
        CkSocket::ckDispose(socket)
        ProcedureReturn
    EndIf

    ;  MaxReadIdleMs controls the inactivity limit for receiving.  The ReceiveBdN call will fail if
    ;  incoming bytes halt for longer than this many milliseconds before the full amount is received.
    CkSocket::setCkMaxReadIdleMs(socket, 15000)

    ;  Receive exactly the requested number of bytes, appending them to a BinData.  The method continues
    ;  receiving until the full count is satisfied or a failure occurs.
    bd.i = CkBinData::ckCreate()
    If bd.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkSocket::ckReceiveBdN(socket,256,bd)
    If success = 0
        Debug CkSocket::ckLastErrorText(socket)
        CkSocket::ckDispose(socket)
        CkBinData::ckDispose(bd)
        ProcedureReturn
    EndIf

    Debug "Received " + Str(CkBinData::ckNumBytes(bd)) + " bytes."


    CkSocket::ckDispose(socket)
    CkBinData::ckDispose(bd)


    ProcedureReturn
EndProcedure