# WebSocket chat

> A chat room on Express and ws: the page talks to the server over a real WebSocket, and bash posts into the same room.

Live: https://clientvm.joeldsouza.me/demos/websocket-chat/ (Chromium) · Source: https://github.com/Reflex-Gravity/client-vm/blob/main/site/src/demos/websocket-chat.ts

The server is the unmodified ws package on an Express app. When the page opens a WebSocket to its own origin, the preview’s service worker hands it to the server listening inside the instance; nothing leaves the tab.

Send a message in the page, or post one from bash with curl: every connected page gets it, and the server logs it in the terminal.

## How it's built

```ts
const app = await vm.createInstance({ fs: { from: { home: { user: { app: chat } } } } });

app.onPortOpen((port, url) => (preview.src = url));
// the page's WebSocket reaches the ws server through the preview's service worker
await app.exec('npm install && npm start', { cwd: '/home/user/app' });
```

## Try

- say from bash: `curl -s --data 'hello from bash' localhost:3000/say`
- who is connected: `curl -s localhost:3000/clients`
- start server: `npm start`

## Built with

Express 4, ws 8, npm 11

## Docs

- [Previews](https://clientvm.joeldsouza.me/docs/decisions/0008-sub-origin-per-port/)
- [Compatibility](https://clientvm.joeldsouza.me/docs/compatibility/)
