websocket
Talk to WebSocket servers: websocket.connect("wss://host/path") gives a connection with send(text), receive(timeout?), each(fn), close() and .open. Text and JSON (maps/lists) messages, TLS for wss://, pings answered automatically, messages up to 16 MB. For the server side see the server library's app.ws().
This library keeps a network connection open, so it needs the TB app on your computer. The examples here show the code; run them with tb file.tb.
import websocket
Example
Needs the TB app on your computer, so there is no Run button here.
import websocket
let ws = websocket.connect("wss://echo.example.com/socket")
ws.send({"hello": "Tanisha"})
say(ws.receive(5))
ws.close()
Functions
connect(url, options?)
returns wsOpen a WebSocket to ws://host:port/path, or to wss://... (TLS).
Options
headersa map of {name: value} to send, for tokens.timeoutseconds to connect and complete the handshake (default: 10).ca_filea PEM file of certificates to trust.insecuretrue to skip certificate checks (testing only).
Example
let ws = websocket.connect("wss://example.com/chat")
ws.send("hello")
say(ws.receive(5))
ws.close()
Visualizehow websocket.connect works
websocket.connect("wss://chat.example.com/live", {"timeout": 10}) gives <ws>
Illustration: example values, drawn from what the function does.
is_url(x)
returns boolTrue if x is text starting with ws:// or wss:// and naming a host.
Visualizehow websocket.is_url works
websocket.is_url("wss://chat.example.com/live") gives truewebsocket.is_url("ws://localhost:8080") gives truewebsocket.is_url("https://example.com") gives false
Real result: worked out by running this example with TB while the site was built.
Values
| Name | Value | What it is |
|---|---|---|
websocket.max_message | 16777216 | The biggest message send() or receive() handles (16 MB). Visualizehow websocket.max_message works
No inputs: call it as it is. Real value, read from TB while the site was built. |
websocket.close_reasons | {1000: "normal", 1001: "going away", 1002: "protocol error", 1003: "unsupport... | What the standard close codes mean. Visualizehow websocket.close_reasons works
No inputs: call it as it is. Real value, read from TB while the site was built. |