Sample code for 30+ languages & platforms
Rust

Socket Receive String Until Specific Byte Value is Received

Demonstrates the Chilkat Socket ReceiveStringUntilByte method.

Chilkat Rust Downloads

Rust

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

let sock = chilkat::Socket::new();

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

let use_tls = false;
let port = 4242;
let mut max_wait_ms = 5000;
if sock.connect("tcpbin.com", port, use_tls, max_wait_ms).is_err() {
    println!("{}", sock.last_error_text());
    return;
}

// Wait a max of 2 seconds for a response..
sock.set_max_read_idle_ms(2000);

// Send some strings, each terminated by a 0 byte.
let _ = sock.send_string("This is the 1st string");
let _ = sock.send_byte(0);
let _ = sock.send_string("This is string number 2");
let _ = sock.send_byte(0);

// The tcpbin.com echo server only echoes after receiving an LF (linefeed char)
let _ = sock.send_byte(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)
let look_for_byte = 0;
let Ok(s1) = sock.receive_string_until_byte(look_for_byte) else {
    println!("{}", sock.last_error_text());
    return;
};

println!("{}", s1);

let Ok(s2) = sock.receive_string_until_byte(look_for_byte) else {
    println!("{}", sock.last_error_text());
    return;
};

println!("{}", s2);

// The echo server will also echo back the final LF
let _ = sock.receive_byte(true);
max_wait_ms = 100;
let _ = sock.close(100);

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