Sample code for 30+ languages & platforms
Zig

Send a 4-byte Length Prefix over a Socket

See more Socket/SSL/TLS Examples

Demonstrates Socket.SendCount, which sends a four-byte length prefix in network byte order. This is typically used to tell the peer how many bytes follow.

Background. A length-prefixed framing scheme sends the byte count of a message before the message body, so the receiver knows exactly how many bytes to read with a counted receive.

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();

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

    // Connect to the server using TLS.
    const b_tls = true;
    const max_wait_ms = 5000;
    socket.connect("example.com", 5000, b_tls, max_wait_ms) catch {
        std.debug.print("{s}\n", .{try socket.getLastErrorText(alloc)});
        return;
    };

    // Send a four-byte length prefix in network byte order.  A common framing pattern is to send the
    // number of bytes in a message before the message itself, so the peer knows exactly how many bytes
    // to read.
    const message_length = 512;
    socket.sendCount(message_length) catch {
        std.debug.print("{s}\n", .{try socket.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("Length prefix sent.\n", .{});
}