websocket API reference
An RFC 6455 WebSocket client over net. connect performs the HTTP Upgrade handshake (verifying the server's Sec-WebSocket-Accept, which is SHA-1 + base64 of the client key), then send / sendBytes write masked text / binary frames and receive reads the next message, transparently answering pings with pongs and reassembling fragmented messages. close sends a close frame and shuts the socket. ws:// is plain TCP, wss:// is TLS.
Client-to-server frames are masked (required by the spec); server frames are not. Needs the default jennifer binary (net); a protocol error or a dropped connection throws Error{kind: "websocket"}. A server-side upgrade is out of scope (it needs an httpd connection-hijack hook).
Import with import "websocket.j" as websocket;. See the websocket guide for prose and examples.
Functions
websocket.close(c as Conn)
Send a close frame and shut the connection.
Parameters
c{Conn}- the connection
websocket.connect(url as string)
Open a WebSocket connection to a ws:// or wss:// URL (default receive timeout).
Parameters
url{string}- the ws:// or wss:// URL
Returns {Conn} - the open connection
Throws
{Error}- kind "websocket" on a failed handshake
websocket.connectWith(url as string, timeoutMs as int)
Open a WebSocket connection with an explicit per-receive read timeout.
Parameters
url{string}- the ws:// or wss:// URLtimeoutMs{int}- the per-receive read timeout in milliseconds
Returns {Conn} - the open connection
Throws
{Error}- kind "websocket" on a failed handshake
websocket.ping(c as Conn)
Send a ping (empty payload).
Parameters
c{Conn}- the connection
websocket.receive(c as Conn)
Receive the next message. Pings are answered with pongs and skipped; fragmented text / binary messages are reassembled. A close frame is returned as kind "close".
Parameters
c{Conn}- the connection
Returns {Message} - the next message
Throws
{Error}- kind "websocket" on a protocol error or dropped connection
websocket.send(c as Conn, text as string)
Send a text message.
Parameters
c{Conn}- the connectiontext{string}- the message text
websocket.sendBytes(c as Conn, data as bytes)
Send a binary message.
Parameters
c{Conn}- the connectiondata{bytes}- the message payload
Structs
websocket.Conn
An open WebSocket connection.
| Field | Type | Description |
|---|---|---|
socket | net.Conn | the underlying (plain or TLS) connection |
timeoutMs | int | the per-receive read timeout in milliseconds |
websocket.Message
A received message.
| Field | Type | Description |
|---|---|---|
kind | string | "text", "binary", "close", or "pong" |
text | string | the decoded text (for a "text" message; "" otherwise) |
data | bytes | the raw payload bytes |