client.login(token). Direct interaction with WebSocketManager and WebSocketShard is not required in most cases.
Connection Lifecycle
WebSocketManagerOptions
WebSocketManager
Manages a pool of shards. Created and started insideclient.login.
connect
/gateway/bot, determines the shard count, and starts each shard in a separate tokio::spawn task.
broadcast
client.send_to_gateway.
send
Err if the shard is not found or its channel is closed.
shard_count
gateway_url
/gateway/bot. None before connect is called.
WebSocketShard
One shard - one WebSocket connection. Manages its own heartbeat and automatically reconnects on disconnect.ShardOptions
Heartbeat
After receivingHello, the shard starts a separate tokio::spawn task:
- The first heartbeat is sent with a random jitter:
sleep(interval * rand()). - After that, a heartbeat is sent every
heartbeat_intervalmilliseconds. - If
HeartbeatAckis not received before the next heartbeat while a session is active - the shard disconnects and reconnects.
rand_f64() in the shard is implemented via SystemTime::subsec_nanos(). This is not cryptographically secure randomness, but it is sufficient for heartbeat jitter.Reconnection
On any disconnect, the shard automatically reconnects with exponential backoff.
After a successful connection, the delay resets to 1,000 ms.
Identify vs Resume
Opcodes
Close Codes
Determine whether to reconnect when aClose frame is received.
Reconnection is performed
Reconnection is not performed
GatewayPresenceUpdateSendData
Set inClientOptions.presence or via send_to_gateway with opcode 3.
GatewayActivity
GatewayCustomStatus
WsEvent / ShardEvent
Internal events that shards pass to the manager.ShardEvent (inside a shard)
WsEvent (from manager to client)
Examples
Set status on startup
Set status on startup
Update status via Gateway at runtime
Update status via Gateway at runtime
Request guild members (RequestGuildMembers)
Request guild members (RequestGuildMembers)
Send VoiceStateUpdate to a specific shard
Send VoiceStateUpdate to a specific shard
Track Debug events from the Gateway
Track Debug events from the Gateway
