Zig
Zig
Socket Receive String Until Specific Byte Value is Received
Demonstrates the Chilkat Socket ReceiveStringUntilByte method.Chilkat Zig Downloads
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;
var max_wait_ms: i32 = 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 some strings, each terminated by a 0 byte.
sock.sendString("This is the 1st string") catch {};
sock.sendByte(0) catch {};
sock.sendString("This is string number 2") catch {};
sock.sendByte(0) catch {};
// The tcpbin.com echo server only echoes after receiving an LF (linefeed char)
sock.sendByte(10) catch {};
// Now let's receive what is echoed back....
// Receive each string and the NULL byte.
// The call to ReceiveStringUntilByte will receive incoming data until the lookForByte is encountered.
// The lookForByte is receive and discarded (it is not returned in the string)
const look_for_byte = 0;
const s1 = sock.receiveStringUntilByte(alloc, look_for_byte) catch {
std.debug.print("{s}\n", .{try sock.getLastErrorText(alloc)});
return;
};
std.debug.print("{s}\n", .{s1});
const s2 = sock.receiveStringUntilByte(alloc, look_for_byte) catch {
std.debug.print("{s}\n", .{try sock.getLastErrorText(alloc)});
return;
};
std.debug.print("{s}\n", .{s2});
// The echo server will also echo back the final LF
sock.receiveByte(true) catch {};
max_wait_ms = 100;
sock.close(100) catch {};
// Output:
// This is the 1st string
// This is string number 2
}