# ProtocolClient

> Documentation for Redweb 0.16.1. Install that exact version when following these examples.

Low-level envelope helper from redweb/client. It wraps a socket you own; it does not connect, reconnect or correlate pending requests. For those features use redweb-client; server TSX pages generate their client integration automatically.

## Explain it like I’m five

ProtocolClient is a phrasebook shared with the browser. It puts outgoing messages into Redweb’s expected envelope and checks incoming envelopes before your code trusts them.

## When should I use it?

Use it when you already own the connection and only need versioned envelopes. Use redweb-client for connection lifecycle and requests, or typed handlers bound to server TSX for generated UI transport.

## Follow the example

This API pattern illustrates the named surface; it may require application-owned classes, credentials, or assets. Start from a complete recipe for a runnable application.

```ts
import { ProtocolClient } from 'redweb/client'

const socket = new WebSocket('wss://game.example/match?redwebVersion=1')
const client = new ProtocolClient(socket, '1')

socket.addEventListener('open', () => {
  client.send('move', { x: 4, y: 2 }, { sequence: 17 })
})

socket.addEventListener('message', event => {
  try {
    const message = client.parse(event)
    console.log(message)
  } catch (error) {
    console.error('Invalid server envelope', error)
  }
})
```

1. Create a WebSocket and its envelope helper, then wait for open before sending.
2. send builds a stable typed envelope containing payload and optional sequence metadata.
3. parse validates server messages so application code can respond to known errors such as rate limiting.

## Methods and members

### constructor(socket, version)

Wraps any socket-like object with send(data) and selects the envelope version.

### envelope(type, payload, metadata?)

Builds a stable versioned event with optional requestId and sequence.

### send(type, payload, metadata?)

Serializes and sends one versioned event through the wrapped socket.

### parse(value)

Parses and validates a protocol event or error envelope.

## What should I watch for?

Bundle this import for browser use; it is not a native script URL. Envelope validation is not payload validation or authorization, and this helper does not replay messages after disconnect.
