Sample code for 30+ languages & platforms
Rust

Socket Send and Receive BinData

Demonstrates the Chilkat Socket ReceiveBdN and SendBd methods.

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 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 26 bytes contained in a Chilkat BinData
let bd_to_send = chilkat::BinData::new();
let mut i = 0;
let mut byte_val = 65;
while i < 26 {
    let _ = bd_to_send.append_byte(byte_val);
    byte_val = byte_val + 1;
    i = i + 1;
}

// Send the contents of the BinData
// Pass zero's in the 2nd and 3rd arguments to send the entire contents of the BinData.
let _ = sock.send_bd(&bd_to_send, 0, 0);

// The tcpbin.com echo server only echoes after receiving an LF (linefeed char)
let _ = sock.send_byte(10);

// The echo server will echo back whatever is sent to it.
// We should be able to read the same bytes back..
let bd_recv = chilkat::BinData::new();
// Receive the 26 bytes previously sent, plus the LF char.
if sock.receive_bd_n(27, &bd_recv).is_err() {
    println!("{}", sock.last_error_text());
    return;
}

// Show the contents of bdRecv in hex format
println!("{}", bd_recv.get_encoded("hex").unwrap_or_default());

// Output:  4142434445464748494A4B4C4D4E4F505152535455565758595A0A