Skip to content

Framing and RPC

Chloë Strainge edited this page Oct 14, 2026 · 1 revision

Framing, server-sent events, and JSON-RPC

A byte stream has no message boundaries. std::net::framing supplies length- prefixed frames and line framing. Length readers accept byte-order, prefix-width, and maximum-payload settings; agree on those settings with the peer.

encode_length creates framed bytes, read_length returns a frame stream, and write_length sends a payload through a Writer. A maximum frame length prevents an untrusted length field from becoming an unbounded allocation request.

Server-sent events

std::net::sse::read adapts a Reader or HTTP response into an item stream of Event values. Events contain data, event, id, and retry. This preserves SSE framing before any JSON/application mapping. Use read_as when event data represents a declared application type.

JSON-RPC without a network dependency

A Router dispatches exact JSON documents to ordinary callbacks. This local example exercises request validation and response construction:

import std::net::rpc
import std::json
let $router = std::net::rpc::Router()
$router.register "greet" fn ($params: std::json::Document | ()): any
{
    "hello"
}
let $reply = $router.dispatch_text '{"jsonrpc":"2.0","id":"a","method":"greet"}'
echo ($reply.require_string "/result")
hello

Handlers can return values or throw CallError with a code, message, and optional data. The router formats protocol errors and avoids sending internal diagnostics to the peer. Notifications have no response; batches retain each request's ID.

A Client accepts an exchange callback, then offers call, call_as, notify, and batch. over_http and over_stream supply transport adapters. Stream-based RPC uses framing and serializes exchanges on its owned transport. Close it when finished, and handle protocol failures rather than reusing a desynchronized stream.


Related: Networking · Item streams · JSON

Clone this wiki locally