Wire Protocol Specification (CK v1)
This document is the single source of truth for the Connekt binary wire protocol shared by Rust (
connekt-core), Android (dev.mobra.connekt), iOS (Connekt), and Browser/H5 (@connekt/client/peer). Any client or server implementing this specification interoperates seamlessly.
1. Design Goals
- Transport-agnostic: The exact same binary framing runs over ADB reverse TCP sockets,
usbmuxdloopback TCP sockets, LAN WebSocket binary messages, and future WAN WSS relays. - Payload-agnostic: Payloads are always opaque raw byte arrays (
bytes). Business modules are demultiplexed bych(channel name) without coupling the wire layer to any application schema. - Three first-class primitives: Unidirectional messages (
DATA, supporting unicast, subset multicast, and*broadcast), correlated RPC (REQ/RESPwithreq_idand timeouts), and zero-copy multiplexed streams (STREAM_OPEN/STREAM_CHUNK/STREAM_CLOSE). - Multi-device, multi-app, multi-link merge: Supports multiple apps on one unrooted phone and automatically merges simultaneous USB + LAN transports under a single
peer_idwith instant failover.
2. Binary Framing
All multi-byte integers are encoded in Big-Endian (Network Byte Order).
2.1 Frame Layout
0 2 3 4 5 9 13 15 19
+------+------+------+------+-----------+-----------+-----------+-----------+--------------------+---------------------+
|Magic | Ver | Type |Flags | ReqID | StreamID | HeaderLen |PayloadLen | Header (UTF-8 JSON)| Payload (raw bytes)|
| (2B) | (1B) | (1B) | (1B) | (4B) | (4B) | (2B) | (4B) | (HeaderLen B) | (PayloadLen B) |
+------+------+------+------+-----------+-----------+-----------+-----------+--------------------+---------------------+- Fixed header size:
19bytes. - Field definitions:
| Offset | Size | Type | Field | Description |
|---|---|---|---|---|
0..2 | 2B | [u8; 2] | magic | Fixed magic 0x43 0x4B (ASCII "CK"). Disconnect immediately on mismatch. |
2 | 1B | u8 | version | Protocol version, fixed at 0x01. |
3 | 1B | u8 | frame_type | Frame type enum (see 2.2 Frame Types). |
4 | 1B | u8 | flags | Bit flags, default 0x00. Bit 0x01 = IS_ERROR (valid on RESP and STREAM_CLOSE); remaining bits reserved. |
5..9 | 4B | u32 | req_id | Request correlation ID. Monotonically incremented per connection starting at 1 (skipping 0) on REQ, echoed verbatim on RESP; 0 on all other frames. |
9..13 | 4B | u32 | stream_id | Stream identifier. 0 for non-stream frames; non-zero u32 for STREAM_* frames enabling frame-level multiplexing. |
13..15 | 2B | u16 | header_len | Byte length of header (0..=65535). 0 indicates no JSON header. |
15..19 | 4B | u32 | payload_len | Byte length of payload. Default max frame payload is 16 MiB (16_777_216 bytes); oversized frames are rejected and disconnected. |
19.. | var | UTF-8 | header | UTF-8 encoded JSON object (present when header_len > 0). |
| following | var | [u8] | payload | Raw opaque payload bytes (present when payload_len > 0). |
WebSocket transport rule: Over WebSocket (
LAN/Relay), every WebSocketBinary Messagecarries one complete frame (19 + header_len + payload_lenbytes), reusing the exact same encoder/decoder as raw TCP streams.
2.2 Frame Types (frame_type)
| Value | Name | Direction | Description |
|---|---|---|---|
0x01 | HELLO | Client → PC | First frame after connect; reports peer identity and device metadata. |
0x02 | HELLO_ACK | PC → Client | Handshake acknowledgement returning Hub info, accepted peer_id, and heartbeat interval. |
0x03 | PING | Bidirectional | Heartbeat probe (header_len = 0, payload_len = 0 or optional timestamp). |
0x04 | PONG | Bidirectional | Heartbeat acknowledgement. |
0x05 | PEER_LIST | PC → Client | Full snapshot of online peers pushed whenever topology or active transport changes. |
0x10 | DATA | Bidirectional / Relayed | Unidirectional message (unicast, dsts subset multicast, or "*" broadcast). |
0x11 | REQ | Bidirectional / Relayed | Request frame expecting a correlated RESP with the same req_id. |
0x12 | RESP | Bidirectional / Relayed | Response frame carrying the matching req_id. |
0x20 | STREAM_OPEN | Bidirectional / Relayed | 0-RTT stream open carrying stream_id, RouteHeader, and optional meta (unicast, subset multicast, or broadcast). |
0x21 | STREAM_CHUNK | Bidirectional / Relayed | Stream data chunk (header_len = 0, zero JSON overhead), routed solely by stream_id. |
0x22 | STREAM_CLOSE | Bidirectional / Relayed | Stream termination: clean EOF (flags = 0, header_len = 0) or abort / receiver reject / cancel (flags = 0x01). |
2.3 Golden Test Vector
All SDKs validate byte-for-byte encoding parity against this vector:
- Input:
version = 1,frame_type = 0x10 (DATA),flags = 0x00,req_id = 0,stream_id = 0header = {"src":"pc","dst":"dev1/appA","ch":"ping"}(42 bytes =0x002A)payload = b"hello"(5 bytes =0x00000005)
- Expected output (
19 + 42 + 5 = 66bytes, hex):
43 4b # magic: "CK"
01 # version: 1
10 # type: DATA (0x10)
00 # flags: 0
00 00 00 00 # req_id: 0
00 00 00 00 # stream_id: 0
00 2a # header_len: 42
00 00 00 05 # payload_len: 5
7b 22 73 72 63 22 3a 22 70 63 22 2c 22 64 73 74 # {"src":"pc","dst
22 3a 22 64 65 76 31 2f 61 70 70 41 22 2c 22 63 # ":"dev1/appA","c
68 22 3a 22 70 69 6e 67 22 7d # h":"ping"}
68 65 6c 6c 6f # "hello"3. Identity & Routing
3.1 Device & Peer Identity
To support multiple apps per device and multi-link merge (USB + LAN) simultaneously:
peer_id(global routing key, generated by the peer SDK and identical across every transport):- Format:
<client_id>/<package_or_bundle_id>(optional:<process_suffix>for multi-process apps). client_idis a persistent 8–12 character random ID stored locally (SharedPreferences/UserDefaults/localStorage).- Because the same app instance reports the exact same
peer_idover both USB and LAN, the PC Hub merges both links automatically.
- Format:
- Reserved addresses:
"pc"— The PC Hub itself."*"— Broadcast to all online peers except the sender (valid forDATAandSTREAM_OPEN, invalid forREQ).
- Physical device grouping:
- Over ADB or usbmuxd, the Hub captures the hardware USB
serial/UDIDand cachespeer_id → serialso device grouping survives unplug failover onto Wi-Fi. - Over LAN-only, peers group by their reported
device_id.
- Over ADB or usbmuxd, the Hub captures the hardware USB
3.2 JSON Header Schemas
1) HELLO (0x01, Client → PC)
payload_len = 0:
{
"peer_id": "a1b2c3d4/com.demo.shop",
"device_id": "dev-9f8e7d6c",
"package_name": "com.demo.shop",
"app_name": "Demo Shop",
"process_name": "com.demo.shop",
"pid": 14820,
"platform": "android",
"model": "Pixel 9",
"manufacturer": "Google",
"os_version": "15",
"transport": "adb",
"sdk_version": "0.1.0"
}2) HELLO_ACK (0x02, PC → Client)
payload_len = 0:
{
"hub_id": "pc",
"hub_version": "0.1.0",
"accepted_peer_id": "a1b2c3d4/com.demo.shop",
"heartbeat_interval_ms": 10000
}3) PEER_LIST (0x05, PC → Client)
Full online snapshot pushed on peer connect, disconnect, or active transport change (payload_len = 0):
{
"peers": [
{
"peer_id": "a1b2c3d4/com.demo.shop",
"device_id": "dev-9f8e7d6c",
"serial": "DEVICE_SERIAL",
"package_name": "com.demo.shop",
"app_name": "Demo Shop",
"model": "Pixel 9",
"os_version": "15",
"transports": ["adb", "lan"],
"active_transport": "adb"
}
]
}4) DATA (0x10) & REQ (0x11)
{
"src": "pc",
"dst": "a1b2c3d4/com.demo.shop",
"ch": "network"
}- Subset multicast (
DATAandSTREAM_OPENonly): Include optionaldstsarray (omitted when empty so unicast/broadcast pay zero overhead):json{ "src": "dev1/com.appA", "dst": "", "dsts": ["pc", "dev2/com.appB"], "ch": "notice" } - Anti-spoofing: On inbound client frames, the Hub always overwrites
srcwith the authenticatedpeer_idof that connection. - Routing rules:
dst == "pc": Delivered to PC Hub handlers and subscribed Control API clients.dst == "*": Broadcast to every online peer exceptsrc, plus PC listeners.- Non-empty
dsts: Deduplicated once inPeerRegistry, excludingsrc, and fanned out zero-copy viaBytes::clone(). - Unicast
peer_id: Routed via the target peer's highest-priority active transport. ForREQto an offline peer, the Hub immediately replies withRESP(flags = 0x01,err_code = "PEER_OFFLINE").
5) RESP (0x12)
Must carry the exact req_id of the originating REQ:
- Success (
flags = 0x00): Raw response bytes inpayload,header = { "src", "dst", "ch" }. - Error (
flags = 0x01):payload_len = 0:json{ "src": "a1b2c3d4/com.demo.shop", "dst": "pc", "ch": "layout", "err_code": "PEER_OFFLINE", "err_msg": "Target peer is not connected" }
6) Multiplexed Streams: STREAM_OPEN (0x20) / STREAM_CHUNK (0x21) / STREAM_CLOSE (0x22)
STREAM_OPEN: 0-RTT stream open with non-zerostream_id,payload_len = 0, standardRouteHeaderplus optionalmeta(Map<String, String>):json{ "src": "pc", "dst": "a1b2c3d4/com.demo.shop", "ch": "files", "meta": { "name": "dump.hprof", "mime": "application/octet-stream" } }- Collision-free remapping: The Hub keys streams by
(src_peer_id, upstream_stream_id)and allocates an independentdownstream_stream_idper downstream link so concurrent senders never collide.
- Collision-free remapping: The Hub keys streams by
STREAM_CHUNK: Hot-path chunk withheader_len = 0. SDKs auto-chunk payloads at 64 KiB by default to prevent head-of-line blocking, and the Hub fans chunks out zero-copy viaBytes::clone().STREAM_CLOSE:- Clean EOF:
flags = 0x00, header_len = 0, payload_len = 0. - Abort / reject / cancel:
flags = 0x01with JSONerr_codeanderr_msg. - Partial multicast reject: If one receiver rejects or disconnects from a multicast stream, the Hub removes only that receiver; the upstream sender is cancelled only when the last receiver exits.
- Bounded queues: Default 32 chunks per stream and 64 concurrent active streams per Hub; abrupt disconnect sends
STREAM_CLOSE(PEER_OFFLINE)to all counterparties and frees routing entries immediately.
- Clean EOF:
3.3 Standard Error Codes (err_code)
| Code | Meaning |
|---|---|
PEER_OFFLINE | Target peer is offline or disconnected mid-flight |
TIMEOUT | Local caller timed out waiting for RESP |
NO_HANDLER | Remote peer has no registered request or stream handler for ch |
HANDLER_ERROR | Remote handler threw an error or sender called abort() |
INVALID_REQUEST | Malformed request (e.g. REQ with "*", empty target list, or stream limit exceeded) |
INTERNAL_ERROR | Internal routing or transport failure |
STREAM_REJECTED | Receiver rejected stream via stream.reject(reason) after inspecting meta |
STREAM_CANCELLED | Receiver cancelled or dropped the stream before EOF |
4. Connection Lifecycle, Heartbeat & Failover
- Handshake timeout: Clients must send
HELLOwithin5sof opening a TCP/WebSocket connection. The Hub replies withHELLO_ACKfollowed byPEER_LIST. - Heartbeat:
- Clients send
PINGevery10s(as advertised inHELLO_ACK); the Hub replies immediately withPONG. - Either side closes the connection if no frame arrives for
30s.
- Clients send
- Reconnect backoff: Exponential backoff
500ms → 1s → 2s → 4s → 5s (cap), resetting on successful handshake. - Multi-link priority:
adb(100) /usbmux(100) >lan(50) >custom(25) >relay(10). Reconnecting on the same(peer_id, transport)smoothly replaces the previous socket.
5. Transport Details
5.1 ADB USB Transport (Android)
- Connects to local ADB server at
127.0.0.1:${ANDROID_ADB_SERVER_PORT:-5037}(spawnsadb start-serveronce if refused). - Streams
host:track-devices-l(falling back tohost:track-devices). - For each online
device<serial>:- Binds an ephemeral local loopback listener
127.0.0.1:0→<local_port>. - Issues
host:transport:<serial>+reverse:forward:tcp:19527;tcp:<local_port>. - Tags all accepted sockets with
transport = "adb"andserial = "<serial>".
- Binds an ephemeral local loopback listener
- On device unplug or graceful Hub shutdown, tears down listeners and cleans up
reverse:killforward:tcp:19527. - On Android,
AdbTransportClientconnects as a plain TCP client to127.0.0.1:19527(only standardINTERNETpermission; 100% zero-root Android 5–15).
5.2 usbmuxd USB Transport (iOS)
- Connects to
/var/run/usbmuxd(macOS/Linux) or127.0.0.1:27015(Windows) using native binary/XML plist framing. - Listens for iOS device attach/detach events and connects into the iOS SDK's local USB loopback listener without requiring Xcode or
iproxy.
5.3 LAN WebSocket & Discovery
- Hub listens on
0.0.0.0:9527(configurable), serving device WebSockets at/ws. - Broadcasts UDP discovery beacons every
2sto port19528(and directed subnet broadcasts) plus Bonjour/mDNS_connekt._tcp:json{ "magic": "connekt", "version": 1, "ws_port": 9527, "hub_name": "MacBook-Pro" } - Peers can also connect via an explicit URL (
ws://<pc_ip>:9527/ws) or QR code when UDP broadcast is restricted by corporate Wi-Fi.