Configure reconnection backoff strategies
mainIf a connection fails, the client automatically attempts to reconnect using a Backoff strategy. You can implement the Backoff interface for custom logic or use one of the three built-in strategies:
- ConstantBackoff: Waits a fixed amount of time between attempts.
- LinearBackoff: Increases the wait time linearly until a
maximumduration is reached. - BinaryExponentialBackoff: Doubles the wait time exponentially until a
maximumStepis reached (Default).
To use a specific strategy, pass it to the backoff parameter in the WebSocket constructor.
// ConstantBackoff: Wait 1s between attempts
const backoff = ConstantBackoff(Duration(seconds: 1));
final socket = WebSocket(uri, backoff: backoff);
// LinearBackoff: Start at 0s, increase by 1s, max 5s
const backoff = LinearBackoff(
initial: Duration(seconds: 0),
increment: Duration(seconds: 1),
maximum: Duration(seconds: 5),
);
final socket = WebSocket(uri, backoff: backoff);
// BinaryExponentialBackoff: Start at 1s, double until step 3
const backoff = BinaryExponentialBackoff(
initial: Duration(seconds: 1),
maximumStep: 3
);
final socket = WebSocket(uri, backoff: backoff);