Use the browser client¶
This page shows how to load Mankai's browser client in a Hanami app, subscribe to a channel, send
actions, and handle dropped connections. The browser client is one JavaScript module,
mankai-sockets.js, with no dependencies. For every option and callback, see
Client API in the reference.
Before you begin¶
Install mankai-sockets and run hanami sockets install. The installer copies the browser client
into your app. For the steps, see
Add your first WebSocket channel.
Load the client¶
Put your page code in a module file, not an inline <script> tag, because Hanami's default Content
Security Policy (script-src 'self') blocks inline scripts. How you load the client depends on
whether your app uses hanami-assets.
The installer copies the client to app/assets/js/mankai-sockets.js. Import it from your entry
point. The asset build bundles it into the script that your layout already loads with
javascript_tag "app":
The installer copies the client to public/js/mankai-sockets.js. Hanami doesn't serve
public/ on its own, so complete the following steps:
-
Serve
public/jswithRack::Static. In production, your proxy can serve it instead: -
Create a module file next to the client that imports it:
-
Load the module file from your template:
-
Restart the server, because you changed
config/app.rb.
After you upgrade the gem, run hanami sockets install again to copy the matching client.
Connect and subscribe¶
To connect, create a consumer with the endpoint's path, create subscriptions, and then call
connect. The following example subscribes to room 42 of the chat channel:
import {createConsumer} from "./mankai-sockets.js";
const consumer = createConsumer("/sockets", {logger: console});
const subscription = consumer.subscriptions.create(
{channel: "chat", params: {room: 42}},
{
connected(data) {
// The server accepted the subscription. You can send actions from here on.
},
received(data) {
// A broadcast arrived on one of the subscription's streams.
},
rejected(reason) {
// The server refused the subscription: "invalid", "unauthorized", or "internal".
},
disconnected() {
// The connection dropped. The client reconnects on its own.
},
},
);
consumer.connect();
No connection opens until you call connect. The path follows the page's scheme, so the client
uses wss: on an https: page. To connect to another host, pass a ws:// or wss:// URL
instead, and use tokens to authenticate.
connected runs after every successful subscribe, including after a reconnect. rejected means
that the subscription is gone; the client doesn't retry it.
Send actions¶
To send an action to the channel, call perform with an action name and data. perform returns a
promise. The following example sends a chat message when the user submits a form:
form.addEventListener("submit", async (event) => {
event.preventDefault();
try {
await subscription.perform("speak", {body: input.value});
input.value = "";
} catch (error) {
status.textContent = `Not sent: ${error.message}`;
}
});
The promise resolves with the data from the channel's Success(data:). It rejects with an
Error whose message is a generic reason, invalid, unauthorized, or internal, when the
channel fails or raises.
perform rejects with not connected until the server accepts the connection. Call it from
connected, or from a user event after connected has run, not right after connect. Keep your
form disabled until connected runs.
Handle dropped connections¶
When the connection drops, the client does the following:
- Runs
disconnectedfor each subscription that the server had accepted. - Rejects pending
performpromises withnot connected. - Reconnects after a random delay that grows with each failed attempt, up to 30 seconds by default.
- Re-sends every subscription except the rejected and unsubscribed ones.
connectedruns again for each subscription that the server accepts.
The client doesn't reconnect after close code 4400, 4401, 4429, or 4430, because the next attempt
fails in the same way. For example, after a disconnect,
the client stays disconnected. For what each code means, see
Close codes.
To change the reconnection delay, pass reconnect in milliseconds:
Unsubscribe and close¶
To end one subscription, call subscription.unsubscribe(). To close the connection for good, call
consumer.close(). A closed consumer never reconnects, and connect does nothing; to connect
again, create a new consumer.