Zig
Zig
Receive a 4-byte Length Prefix from a Socket
See more Socket/SSL/TLS Examples
Demonstrates Socket.ReceiveCount, which reads a four-byte length prefix as a signed 32-bit integer. A return value of -1 indicates failure.
Background. Reading the length prefix first tells the application exactly how many bytes to read for the message body, which is a reliable way to know when a full message has arrived.
Chilkat Zig Downloads
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;
};
// Read a four-byte length prefix as a signed 32-bit integer (network byte order by default). A
// return value of -1 indicates failure.
const message_length = socket.receiveCount();
if (message_length < 0) {
std.debug.print("{s}\n", .{try socket.getLastErrorText(alloc)});
return;
}
std.debug.print("The peer will send {d} bytes.\n", .{message_length});
}