Skip to main content
The Gateway connection is managed automatically via 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 inside client.login.

connect

Fetches /gateway/bot, determines the shard count, and starts each shard in a separate tokio::spawn task.

broadcast

Sends a JSON payload to all active shards. Called via client.send_to_gateway.

send

Sends a JSON payload to a specific shard by its ID. Returns Err if the shard is not found or its channel is closed.

shard_count

Returns the total number of running shards.

gateway_url

Returns the WebSocket URL received from /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 receiving Hello, the shard starts a separate tokio::spawn task:
  1. The first heartbeat is sent with a random jitter: sleep(interval * rand()).
  2. After that, a heartbeat is sent every heartbeat_interval milliseconds.
  3. If HeartbeatAck is 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 a Close frame is received.

Reconnection is performed

Reconnection is not performed

When code 4004 is received, the shard shuts down without reconnecting. Verify that the token is correct.

GatewayPresenceUpdateSendData

Set in ClientOptions.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