libipc/examples/pong.zig

91 lines
2.6 KiB
Zig

// Example of a `pong` client using the Zig library directly (not the C bindings).
const std = @import("std");
const ipc = @import("ipc");
const hexdump = ipc.hexdump;
const Message = ipc.Message;
const util = ipc.util;
const builtin = @import("builtin");
const native_os = builtin.target.os.tag;
const print = std.debug.print;
const testing = std.testing;
const service_name = "pong";
fn create_service() !void {
var gpa = std.heap.DebugAllocator(.{.safety = true}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var ctx = try ipc.Context.init(allocator);
defer {
std.debug.print("Deinit context.\n", .{});
ctx.deinit(); // There. Can't leak. Isn't Zig wonderful?
}
// CLIENT SIDE: connect to a service.
const servicefd = try ctx.connect_service(service_name);
// Listen to the standard input (to quit the application).
try ctx.add_external(0);
// Schedule a message.
const message = try Message.init(servicefd, allocator, "hello, plz bounce me");
try ctx.schedule (message);
var some_event: ipc.Event = undefined;
ctx.timer = 20000; // 2 seconds
var count: u32 = 0;
var should_continue = true;
while(should_continue) {
some_event = try ctx.wait_event();
switch (some_event.t) {
.EXTERNAL => {
should_continue = false;
},
.TIMER => {
std.debug.print("\rTimer! ({d})", .{count});
count += 1;
},
.CONNECTION => {
std.debug.print("Connection.\n", .{});
},
.DISCONNECTION => {
std.debug.print("Disconnection.\n", .{});
},
.MESSAGE_RX => {
if (some_event.m) |m| {
std.debug.print("Message received from {d} ({d} bytes)\n", .{m.fd, m.payload.len});
util.print_message ("RECEIVED MESSAGE", m);
should_continue = false;
m.deinit();
}
else {
std.debug.print("Error while receiving new message. Ignoring.\n", .{});
}
},
.MESSAGE_TX => {
std.debug.print("Message sent to {d}.\n", .{some_event.origin});
},
else => {
std.debug.print("Error: unexpected event\n", .{});
std.debug.print("Quitting.\n", .{});
should_continue = false;
},
}
}
std.debug.print("Goodbye\n", .{});
}
pub fn main() !u8 {
try create_service();
return 0;
}