# WebSocket requests

> Connect to WebSocket servers from Cloak Proxy's API client, send text, binary and ping frames, save messages, and test replies in the collection runner.

Source: https://docs.subcloak.com/cloak-proxy/api-client/protocols/websocket/

A WebSocket request opens a live, two-way connection to a `ws://` or `wss://` server. Once connected, you send text or binary messages and watch everything the server sends back in a timestamped log. Use it to try a realtime API by hand, to reproduce a bug in a chat or notification service, or, saved in a collection, to check a server's reply in the collection runner.

## Connect and send messages

1. In the API client, click **New › Other Protocols › WebSocket**, or right-click a collection and choose **Add Other Request › WebSocket**. Search Everything (<kbd>⇧</kbd> <kbd>⌘</kbd> <kbd>A</kbd>) also has **New WebSocket Request**.

   The new request points at a public echo server, `wss://echo.websocket.org`.

2. Type the server's URL, for example `wss://api.example.com/socket`. Include the scheme: `ws://` for plain connections, `wss://` for TLS.

3. Add any handshake headers in **Headers**, and subprotocols in **Settings**.

4. Press <kbd>⌘</kbd> <kbd>↩</kbd> or click **Connect**. The dot next to the button turns green and the status reads **Connected**.

5. Write a message in **Message** and press <kbd>⌘</kbd> <kbd>⇧</kbd> <kbd>↩</kbd> or click **Send**.

6. Click **Disconnect** when you're done.

*[Screenshot: A WebSocket request to wss://echo.websocket.org, disconnected, with a JSON message in the Message tab and Ping, Send Binary (hex) and Send buttons. A WebSocket request before connecting.]*

The connection belongs to the request, not the tab: switching to another request and back keeps it open.

## Request tabs

| Tab | Field | What it does |
|---|---|---|
| **Message** | Editor | The message to send. `{{variables}}` are filled in when you send. |
| **Message** | **Saved** | **Save Current Message** keeps the editor's text, named after its first 30 characters. Choose a saved message to load it, or remove one with **Delete**. |
| **Headers** | Key/value table | Extra headers for the opening HTTP handshake, such as `Authorization` or `Cookie`. Keys and values can use `{{variables}}`. |
| **Settings** | **Subprotocols (comma separated)** | Values for `Sec-WebSocket-Protocol`, for example `graphql-transport-ws, json`. The server's choice appears in the **Connected** log entry. |
| **Settings** | **Skip TLS certificate verification** | Accepts any certificate on `wss://` connections, for development servers. |

`{{variables}}` also work in the URL.

## Send text, binary and ping frames

All three buttons are enabled only while connected.

| Button | Sends |
|---|---|
| **Send** | The editor's text as a text frame. |
| **Send Binary (hex)** | The editor's text read as hex bytes (for example `de ad be ef`, `0xdeadbeef` or `de:ad:be:ef`) as a binary frame. |
| **Ping** | A ping frame. The log shows **Pong after 12.3 ms** when the server answers. |

**Text**

```json title="Message, sent with Send"
{ "type": "subscribe", "channel": "orders", "token": "{{token}}" }
```

**Binary (hex)**

```text title="Message, sent with Send Binary (hex)"
81 a4 74 79 70 65 a4 70 69 6e 67
```

Cloak Proxy answers the server's pings automatically, and accepts messages up to 16 MB.

## Read the Messages log

Each event of the connection is an entry with a time down to the millisecond:

| Entry | Meaning |
|---|---|
| **Connecting to** … | The handshake started. |
| **Connected · 101 · subprotocol · 85 ms** | The handshake succeeded. Select it to see the server's handshake headers. |
| **Sent** / **Received** | A text message, outgoing (blue arrow) or incoming (green arrow). |
| **Binary 128 bytes** | A binary message. |
| **Ping** / **Pong** | Control frames. |
| **Close frame** | The close frame with its code and reason. |
| **Disconnected (1000) by you** | The connection closed. "by you" means you clicked **Disconnect**. |
| **Error** / **Couldn't connect** | A failure, with the reason. |

Select an entry to see its content below the list: JSON as a collapsible tree, text as text, and binary as a hex dump. **Hide events** hides informational entries such as connects and pings, the search field filters by title and content, and **Clear** empties the log. The log keeps the last 5,000 entries.

## Run WebSocket requests in the collection runner

The [collection runner](https://docs.subcloak.com/cloak-proxy/api-client/run/collection-runner/) and [`cloakctl`](https://docs.subcloak.com/cloak-proxy/automation/cloakctl/) run a saved WebSocket request in one step: connect, send the **Message** once as a text frame (nothing is sent if it's empty), collect what comes back, and disconnect. Collecting stops when no new message has arrived for half a second, when the server closes the connection, or after the request timeout (30 seconds by default) if nothing arrives at all.

The result is turned into an HTTP-style response so tests can check it:

| Response part | Value |
|---|---|
| Status | The handshake status, normally `101 Switching Protocols`. |
| Headers | The server's handshake headers, plus `x-messages-received` with the number of messages collected. |
| Body | One message: the message itself (pretty-printed when it's JSON). Several: a JSON array of them. Binary messages appear as base64 strings. |

WebSocket requests have no **Scripts** tab of their own. Put tests in the collection's or a folder's post-response script, and check `pm.info.requestName` when a test is only for this request:

```js title="Collection post-response script"
if (pm.info.requestName === "Echo socket") {
  pm.test("server replied", () => {
    pm.expect(Number(pm.response.headers.get("x-messages-received"))).to.be.above(0);
  });
  pm.test("reply is the welcome event", () => {
    pm.expect(pm.response.json().type).to.eql("welcome");
  });
}
```

A failed handshake or a refused connection is reported as an error with no response.

> **Not through Cloak Proxy:**
> WebSocket requests from the API client connect straight to the server, so they don't appear in the main traffic list. To inspect WebSocket traffic from your own apps, capture it and use the WebSocket view in the inspector. See [WebSocket and GraphQL](https://docs.subcloak.com/cloak-proxy/inspect/websocket-and-graphql/).

> **Credentials in headers:**
> Handshake headers are saved with the request in your workspace files. Put tokens in a secret environment variable or the [vault](https://docs.subcloak.com/cloak-proxy/api-client/variables-and-environments/) and reference them, as in `Bearer {{token}}`, so they stay out of Git and exports.

## Related

  - [Socket.IO requests](https://docs.subcloak.com/cloak-proxy/api-client/protocols/socket-io/): Events, namespaces and acknowledgements on Socket.IO servers.
  - [WebSocket and GraphQL](https://docs.subcloak.com/cloak-proxy/inspect/websocket-and-graphql/): Inspect WebSocket frames your apps send.
  - [Collection runner](https://docs.subcloak.com/cloak-proxy/api-client/run/collection-runner/): Run realtime requests with tests.
  - [Scripts and tests](https://docs.subcloak.com/cloak-proxy/api-client/scripts-and-tests/): The pm API for checking responses.
