JavaScript API
import { connect, attach, list, SocketIoError } from 'tauri-plugin-socketio-api'
const socket = await connect('chat', {
url: 'https://chat.example.com', // the path is the namespace, like socket.io-client
auth: { token },
transports: ['websocket'], // default: polling upgraded to websocket
reconnectionDelay: 500,
events: ['message', 'typing'], // optional: forward only these events to this webview
})
socket.on('message', (text, from) => console.log(from, text))
socket.on('question', (q, ack) => ack('answer')) // the server emitted with a callback
socket.onAny((event, ...args) => console.debug(event, args))
const off = socket.onState((s) => console.log(s.status))
await socket.emit('message', 'hi', new Uint8Array([1, 2, 3]))
const [sum] = await socket.emitWithAck('add', [1, 2], { timeout: 5000 })
Functions
| Function | What |
|---|---|
connect(id, options) | connects a new client under id, owned by the webviews (Access::Full), and subscribes to it |
attach(id, { events? }) | subscribes to a registered client (one Rust registered, or one connected before a reload) |
list() | [{ id, access: 'full' | 'readOnly', namespace, state }] |
encodeArgs(args) / decodeArgs({ args, binary }) | the binary encoding used on the IPC |
Ids are unique. connect with an id in use rejects with AlreadyExists, typically after a page reload, since the client lives in Rust. attach(id) to it, or disconnect it first.
const socket = await connect('chat', { url }).catch((e) => {
if (e instanceof SocketIoError && e.kind === 'AlreadyExists') return attach('chat')
throw e
})
Options
Durations are in milliseconds.
| Option | What |
|---|---|
url | server URL; its path is the namespace |
namespace, path | namespace, engine.io path (default /socket.io/) |
query, headers | query parameters, extra headers (extraHeaders; some are refused) |
auth | the CONNECT payload |
transports | ['polling', 'websocket'] (default: polling upgraded to websocket), ['websocket'], ['polling'] or 'websocket-upgrade' (the upgrade must succeed) |
timeout | one connect attempt (handshake + upgrade + CONNECT), default 20000 |
reconnection, reconnectionAttempts, reconnectionDelay, reconnectionDelayMax, randomizationFactor | backoff, as in socket.io-client |
reconnectOnDisconnect, bufferWhileDisconnected | see Configuration |
ca | PEM certificates to trust instead of the default roots (a private CA); certificate checks cannot be turned off |
events | forwarding filter: only these events reach this webview (state is always forwarded) |
A wrong option type or value rejects with InvalidOptions (the value is not echoed).
Socket
| Member | What |
|---|---|
emit(event, ...args) | sends; rejects with NotConnected, AccessDenied, ... |
emitWithAck(event, args, { timeout }) | resolves with the ack's arguments (default timeout 10 s) |
on, once, off(event, listener?) | event listeners; the last argument is an ack function when the server passed a callback (calling it again does nothing; a failed answer is logged). off(event, fn) also removes once(event, fn). A throwing listener does not stop the others |
on('connect' | 'disconnect' | 'connect_error', …) | from the state transitions, as in socket.io-client: disconnect gets the reason, connect_error a SocketIoError |
onAny, offAny | every event |
onState(listener) | state changes; returns an unsubscribe function |
connected, id, lastState | the latest state seen, synchronously |
state(), linkInfo() | ask Rust; LinkInfo mirrors the Rust one (times as Unix epoch milliseconds) |
setAuth(auth), setHeaders(headers), setQuery(query) | used from the next connect attempt |
reconnect() | connects a closed client again (rejected, attempts used up, server disconnect) |
close() | stops receiving in this webview; the client stays connected |
disconnect() | leaves, closes and unregisters the client (every webview sees closed; this socket reports it as soon as the call resolves) |
Auth, headers and query are read again before every connect attempt, so setAuth / setHeaders / setQuery take effect on the next reconnect. They and reconnect work on clients a webview connected; they fail with NotConfigurable on Rust's clients and AccessDenied on read-only ones.
States are { status: 'connecting' | 'connected' | 'disconnected' | 'reconnecting' | 'closed', ... }, see Messages and errors.
Timing
connect attaches the subscription before connecting, so the events the server sends right after the connect are not lost. When connect / attach resolve, the socket already has the current state (socket.connected, socket.id); messages are held until the call resolved and the subscription's snapshot (its first state message) arrived, then dispatched in the next task (states older than the snapshot are dropped). Add handlers right after the await.
Binary
Uint8Array, ArrayBuffer, typed arrays, DataViews, Blobs and Files anywhere in the arguments are sent as socket.io attachments; incoming attachments arrive as Uint8Arrays. On the IPC they are { args, binary }, where {"_placeholder":true,"num":n} in args stands for binary[n] (socket.io-parser's encoding). Without attachments nothing is replaced: a JSON object that looks like a placeholder stays JSON. Bytes cross the IPC as arrays of numbers, so prefer the websocket for large blobs.
Errors
Rejections are SocketIoError with kind, message and data; see Messages and errors.
try {
await socket.emitWithAck('save', [doc], { timeout: 3000 })
} catch (e) {
if (e instanceof SocketIoError && e.kind === 'AckTimeout') retry()
}