Sample code for 30+ languages & platforms
Zig

TCP Socket Send Byte and Receive Byte

Demonstrates the Chilkat Socket ReceiveByte and SendByte method.

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 a byte.
    sock.sendByte(96) 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 byte back..
    // After successfully reading, the byte value is available in the ReceivedInt property.
    const treat_as_unsigned_int = true;
    sock.receiveByte(treat_as_unsigned_int) catch {
        std.debug.print("{s}\n", .{try sock.getLastErrorText(alloc)});
        return;
    };

    // Let's look at the value of the byte received.  It should be 96.
    std.debug.print("{d}\n", .{sock.getReceivedInt()});

    // The echo server also echoed the LF back.
    try sock.receiveByte(treat_as_unsigned_int);
    // Assuming success..

    // Should be decimal 10.
    std.debug.print("{d}\n", .{sock.getReceivedInt()});
}