Sample code for 30+ languages & platforms
Zig

Socket Send and Receive BinData

Demonstrates the Chilkat Socket ReceiveBdN and SendBd methods.

Chilkat Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

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

    const sock = try chilkat.Socket.init();
    defer sock.deinit();

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

    const use_tls = false;
    const port = 4242;
    const max_wait_ms = 5000;
    sock.connect("tcpbin.com", port, use_tls, max_wait_ms) catch {
        std.debug.print("{s}\n", .{try sock.getLastErrorText(alloc)});
        return;
    };

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

    // Send 26 bytes contained in a Chilkat BinData
    const bd_to_send = try chilkat.BinData.init();
    defer bd_to_send.deinit();
    var i: i32 = 0;
    var byte_val: i32 = 65;
    while (i < 26) {
        bd_to_send.appendByte(byte_val) catch {};
        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.
    sock.sendBd(bd_to_send, 0, 0) catch {};

    // The tcpbin.com echo server only echoes after receiving an LF (linefeed char)
    sock.sendByte(10) catch {};

    // The echo server will echo back whatever is sent to it.
    // We should be able to read the same bytes back..
    const bd_recv = try chilkat.BinData.init();
    defer bd_recv.deinit();
    // Receive the 26 bytes previously sent, plus the LF char.
    sock.receiveBdN(27, bd_recv) catch {
        std.debug.print("{s}\n", .{try sock.getLastErrorText(alloc)});
        return;
    };

    // Show the contents of bdRecv in hex format
    std.debug.print("{s}\n", .{try bd_recv.getEncoded(alloc, "hex")});

    // Output:  4142434445464748494A4B4C4D4E4F505152535455565758595A0A
}