Skip to content

WebSocket

The client can also open WebSocket connections, with the same http.Client you use for other requests. Pass a ws:// URL to client.connectWebSocket, and you get back an http.WebSocketClient to send and receive messages on.

This example talks to the echo server from the server docs:

var ws = try client.connectWebSocket("ws://127.0.0.1:8080/ws", .{});
defer ws.deinit();

try ws.send(.text, "hello");

const msg = try ws.receive();
std.debug.print("{s}\n", .{msg.data});

try ws.close(.normal, "bye");

If the server doesn't accept the upgrade, connectWebSocket returns error.WebSocketUpgradeFailed.

ws.send, ws.receive, ws.ping and ws.close work the same as on an http.WebSocket in a handler. See the server WebSocket page. ws.deinit() drops the connection without sending a close message. Call ws.close first, as the example does.

wss:// URLs connect over TLS and use the client's TLS settings.

Options

The second argument to connectWebSocket holds the options. .headers are sent with the upgrade request, for example an Authorization header. .unix_socket_path connects over a Unix socket instead of TCP.

Next Steps