Sample code for 30+ languages & platforms
Swift

Socket Receive String Until Specific Byte Value is Received

Demonstrates the Chilkat Socket ReceiveStringUntilByte method.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

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

    let sock = CkoSocket()!

    // --------------------------------------------------------------------
    // This example uses the public TCP echo service at https://tcpbin.com/
    // --------------------------------------------------------------------

    var useTls: Bool = false
    var port: Int = 4242
    var maxWaitMs: Int = 5000
    success = sock.connect(hostname: "tcpbin.com", port: port, ssl: useTls, maxWaitMs: maxWaitMs)
    if success == false {
        print("\(sock.lastErrorText!)")
        return
    }

    // Wait a max of 2 seconds for a response..
    sock.maxReadIdleMs = 2000

    // Send some strings, each terminated by a 0 byte.
    sock.sendString(str: "This is the 1st string")
    sock.sendByte(value: 0)
    sock.sendString(str: "This is string number 2")
    sock.sendByte(value: 0)

    // The tcpbin.com echo server only echoes after receiving an LF (linefeed char)
    sock.sendByte(value: 10)

    // Now let's receive what is echoed back....
    // Receive each string and the NULL byte.
    // The call to ReceiveStringUntilByte will receive incoming data until the lookForByte is encountered.
    // The lookForByte is receive and discarded (it is not returned in the string)
    var lookForByte: Int = 0
    var s1: String? = sock.receiveString(untilByte: lookForByte)
    if sock.lastMethodSuccess == false {
        print("\(sock.lastErrorText!)")
        return
    }

    print("\(s1!)")

    var s2: String? = sock.receiveString(untilByte: lookForByte)
    if sock.lastMethodSuccess == false {
        print("\(sock.lastErrorText!)")
        return
    }

    print("\(s2!)")

    // The echo server will also echo back the final LF
    sock.receiveByte(bUnsigned: true)
    maxWaitMs = 100
    sock.close(maxWaitMs: 100)

    // Output:
    // This is the 1st string
    // This is string number 2

}