Implement a custom handler with a background read loop
masterFor advanced usage, wrap websocket.Client in a custom struct and use a background read loop. This allows you to use callback-style methods instead of manual polling.
- Define a struct that contains the
websocket.Client. - Implement the required
serverMessage(self: *Handler, data: []u8) !voidmethod. To distinguish between text and binary, you can use the overload:serverMessage(self: *Handler, data: []u8, tpe: ws.MessageTextType) !void. - Implement optional callbacks:
close(self: *Handler) void: Called exactly once when the read loop exits.serverPing(self: *Handler, data: []u8) !void: Called on ping. If omitted, the library automatically replies with a pong.serverPong(self: *Handler) !void: Called on pong. If omitted, the library ignores the message.serverClose(self: *Handler) !void: Called on close. Note: It is recommended to implementclose()instead ofserverClose(). In yourclose()callback, callclient.close(.{})to terminate the connection.
- Start the loop using
client.readLoop(handler)(blocking) orclient.readLoopInNewThread(handler)(non-blocking).
Warning: It is not safe to call client.read() manually while a read loop is running.
const ws = @import("websocket");
const Handler = struct {
client: ws.Client,
fn serverMessage(self: *Handler, data: []u8) !void {
return self.client.write(data);
}
fn close(self: *Handler) void {
// Handle cleanup
}
pub fn startLoop(self: *Handler) !void {
const thread = try self.client.readLoopInNewThread(self);
thread.detach();
}
};