Client · In depth

ProtocolClient

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

The simple mental model

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 it fits

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.

A practical API pattern

Follow the example

This pattern explains the named API. Application classes, credentials, and assets may need to be supplied; use a complete recipe for a runnable starting point.

Read this article as Markdown

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. 1

    Create a WebSocket and its envelope helper, then wait for open before sending.

  2. 2

    send builds a stable typed envelope containing payload and optional sequence metadata.

  3. 3

    parse validates server messages so application code can respond to known errors such as rate limiting.

Surface area

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.