> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hyperwisor.com/llms.txt
> Use this file to discover all available pages before exploring further.

# ws

> Send and receive realtime messages from a script.

The `ws` global is your script's access to the realtime channel — the same
channel devices use.

## Platform-routed messaging

Use these for normal device communication. The platform routes by target ID.

```js theme={null}
// Send a payload to a target (e.g. a device)
ws.send(targetId, payload);

// Receive messages; returns an unsubscribe function
const off = ws.onMessage((message) => {
  console.log('received', message);
});
// later: off();
```

<Tip>
  `ws.send` / `ws.onMessage` are the right tools for talking to devices — they go
  through the platform's realtime routing, so you only need the target ID.
</Tip>

## Connecting to your own server

For advanced cases, a script can open a connection to **your own** external
WebSocket server (not the platform's). Pass the URL you control:

```js theme={null}
await ws.connect(url, (data) => { /* messages from your server */ });
ws.sendTo(url, data);          // send to that connection
ws.isConnected(url);           // boolean
ws.disconnect(url);            // close it
```

<Warning>
  `connect` / `sendTo` / `disconnect` are for **external servers you operate**.
  Don't use them to reach platform internals — use `ws.send` / `ws.onMessage` for
  device communication.
</Warning>

<Card title="Next: storage" icon="box-archive" href="/script/storage-api">
  Persist small values on the client.
</Card>
