websocket
websocket.zig docs client.md
9.9 kB · 244 lines
Markdown
at main

client #

this guide is Karl Seguin's upstream documentation for karlseguin/websocket.zig, MIT-licensed. its examples predate Zig 0.17; the client is constructed with a std.Io. upgrading from an older version: the upstream client migration wiki.

The *websocket.Client can be used in one of two ways. At its simplest, after creating a client and initiating a handshake, you simply use write to send messages and read to receive them. First, we create the client and initiate the handshake:

pub fn main() !void {
  var gpa = std.heap.GeneralPurposeAllocator(.{}){};
  const allocator = gpa.allocator();

  // create the client
  var client = try websocket.Client.init(allocator, .{
    .port = 9224,
    .host = "localhost",
  });
  defer client.deinit();

  // send the initial handshake request
  const request_path = "/ws";
  try client.handshake(request_path, .{
    .timeout_ms = 1000,
    // Raw headers to send, if any. 
    // A lot of servers require a Host header.
    // Separate multiple headers using \r\n
    .headers = "Host: localhost:9224",
  });
}

We can then use read and write. By default, read blocks until a message is received (or an error occurs). We can make it return null by setting a timeout:

  // optional, read will return null after 1 second
  try client.readTimeout(std.time.ms_per_s * 1);

  // echo messages back to the server until the connection is closed
  while (true) {
    // since we didn't set a timeout, client.read() will either
    // return a message or an error (i.e. it won't return null)
    const message = (try client.read()) orelse {
        // no message after our 1 second
        std.debug.print(".", .{});
        continue;
    };

    // must be called once you're done processing the request
    defer client.done(message);

    switch (message.type) {
      .text, .binary => {
        std.debug.print("received: {s}\n", .{message.data});
        try client.write(message.data);
      },
      .ping => try client.writePong(message.data),
      .pong => {},
      .close => {
        try client.close(.{});
        break;
      }
    }
  }
}

Config #

When creating a Client, the 2nd parameter is a configuration object:

  • port - The port to connect to. Required.
  • host - The host/IP address to connect to. The Host:IP value IS NOT automatically put in the header of the handshake request. Required.
  • max_size - Maximum incoming message size to allow. The library will dynamically allocate up to this much space per request. Default: 65536.
  • buffer_size - Size of the static buffer that's available for the client to process incoming messages. While there's other overhead, the minimal memory usage of the server will be # of active clients * buffer_size. Default: 4096.
  • tls - Whether or not to connect over TLS. Only TLS 1.3 is supported. Default: false.
  • ca_bundle - Provide a custom std.crypto.Certificate.Bundle. Only meaningful when tls = true. Default: null.

Setting max_size == buffer_size is valid and will ensure that no dynamic memory allocation occurs once the connection is established.

Zig only supports TLS 1.3, so this library can only connect to hosts using TLS 1.3. If no ca_bundle is provided, the library will create a default bundle per connection.

Handshake #

client.handshake() takes two parameters. The first is the request path. The second is handshake configuration value:

  • timeout_ms - Timeout, in milliseconds, for the handshake. Default: 10_000 (10 seconds).
  • headers - Raw headers to include in the handshake. Multiple headers should be separated by by "\r\n". Many servers require a Host header. Example: "Host: server\r\nAuthorization: Something". Defaul: null

Custom Wrapper #

In more advanced cases, you'll likely want to wrap a *ws.Client in your own type and use a background read loop with "callback" methods. Like in the above example, you'll first want to create a client and initialize a handshake:

const ws = @import("websocket");

const Handler = struct {
  client: ws.Client,

  fn init(allocator: std.mem.Allocator) !Handler {
    var client = try ws.Client.init(allocator, .{
      .port = 9224,
      .host = "localhost",
    });
    defer client.deinit();

     // send the initial handshake request
    const request_path = "/ws";
    try client.handshake(request_path, .{
      .timeout_ms = 1000,
      .headers = "host: localhost:9224\r\n",
    });

    return .{
      .client = client,
    };
  }

You can then call client.readLoopInNewThread() to start a background listener. Your handler must define a serverMessage method:

  pub fn startLoop(self: *Handler) !void {
    // use readLoop for a blocking version
    const thread = try self.client.readLoopInNewThread(self);
    thread.detach();
  }

  pub fn serverMessage(self: *Handler, data: []u8) !void {
    // echo back to server
    return self.client.write(data);
  }
}

Websockets have a number of different message types. serverMessage only receives text and binary messages. If you care about the distinction, you can use an overload:

pub fn serverMessage(self: *Handler, data: []u8, tpe: ws.MessageTextType) !void

where tpe will be either .text or .binary. Different callbacks are used for the other message types.

Optional Callbacks #

In addition to the required serverMessage, you can define optional callbacks.

// Guaranteed to be called exactly once when the readLoop exits
pub fn close(self: *Handler) void

// If omitted, websocket.zig will automatically reply with a pong
pub fn serverPing(self: *Handler, data: []u8) !void

// If omitted, websocket.zig will ignore this  message
pub fn serverPong(self: *Handler) !void

// If omitted, websocket.zig will automatically reply with a close message
pub fn serverClose(self: *Handler) !void

You almost certainly do not want to define a serverClose method, but instead what do define a close method. In your close callback, you should call client.close(.{}) (and optionally pass a code and reason).

Client #

Whether you're calling client.read() explicitly or using client.readLoopInNewThread() (or client.readLoop()), the client API is the same. In both cases, the various write methods, as well as close() are thread-safe.

Writing #

It may come as a surprise, but every variation of write expects a []u8, not a []const u8. Websocket payloads sent from a client need to be masked, which the websocket.zig library handles. It is obviously more efficient to mutate the given payload versus creating a copy. By taking a []u8, applications with mutable buffers benefit from avoiding the clone. Applications that have immutable buffers will need to create a mutable clone.

// write a text message
pub fn write(self: *Client, data: []u8) !void

// write a text message (same as client.write(data))
pub fn writeText(self: *Client, data: []u8) !void

// write a binary message
pub fn writeBin(self: *Client, data: []u8) !void

// write a ping message
pub fn writePing(self: *Client, data: []u8) !void

// write a pong message
// if you don't define a handlePong message, websocket.zig
// will automatically answer any ping with a pong
pub fn writePong(self: *Client, data: []u8) !void

// lower-level, use by all of the above
pub fn writeFrame(self: *Client, op_code: proto.OpCode, data: []u8) !void

Reading #

As seen above, most applications will either chose to call read() explicitly or use a readLoop. It is *not safe to call read while the read loop is running.

// Reads 1 message. Returns null on timeout
// Set a timeout using `client.readTimeout(ms)`
pub fn read(self: *Client) !?ws.Message


// Starts a readloop in the calling thread. 
// `@TypeOf(handler)` must define the `serverMessage` callback
// (and may define other optional callbacks)
pub fn readLoop(self: *Client, handler: anytype) !void

// Same as `readLoop` but starts the readLoop in a new thread
pub fn readLoopInNewThread(self: *Client, h: anytype) !std.Thread

Closing #

Use try client.close(.{.code = 4000, .reason = "bye"}) to both send a close frame and close the connection. Noop if the connection is already known to be close. Thread safe.

Both code and reason are optional. Refer to RFC6455 for valid codes. The reason must be <= 123 bytes.

Performance Optimization 1 - CA Bundle #

For a high number of connections, it might be beneficial to manage our own CA bundle:

// some global data
var ca_bundle = std.crypto.Certificate.Bundle{}
try ca_bundle.rescan(allocator);
defer ca_bundle.deinit(allocator);

And then assign this ca_bundle into the the configuration's ca_bundle field. This way the library does not have to create and scan the installed CA certificates for each client connection.

Performance Optimization 2 - Buffer Provider #

For a high nummber of connections a large buffer pool can be created and provided to each client:

// Create a buffer pool of 10 buffers, each being 32K
const buffer_provider = try websocket.bufferProvider(allocator, 10, 32768);
defer buffer_provider.deinit();


// create your client(s) using the above created buffer_provider
var client = try websocket.connect(allocator, "localhost", 9001, .{
    ...
    .buffer_provider = buffer_provider,
});

This allows each client to have a reasonable buffer_size that can accomodate most messages, while having an efficient fallback for the occasional large message. When max_size is greater than the large buffer pool size (32K in the above example) or when all pooled buffers are used, a dynamic buffer is created.