### Custom Backoff Strategy Implementation (Dart) Source: https://context7.com/felangel/web_socket_client/llms.txt Demonstrates how to implement a custom reconnection strategy by creating a class that adheres to the Backoff interface. This example uses a Fibonacci sequence for calculating wait times, allowing for tailored reconnection logic based on specific application needs. ```dart import 'package:web_socket_client/web_socket_client.dart'; // Custom backoff with Fibonacci sequence class FibonacciBackoff implements Backoff { FibonacciBackoff({required this.initial, this.maximum}); final Duration initial; final Duration? maximum; int _previous = 0; int _current = 1; @override Duration next() { final milliseconds = _current * initial.inMilliseconds; final duration = Duration(milliseconds: milliseconds); // Calculate next Fibonacci number final next = _previous + _current; _previous = _current; _current = next; // Apply maximum if specified if (maximum != null && duration > maximum!) { return maximum!; } return duration; } @override void reset() { _previous = 0; _current = 1; } } void main() { // Pattern: [100ms, 100ms, 200ms, 300ms, 500ms, 800ms, ...] final fibBackoff = FibonacciBackoff( initial: Duration(milliseconds: 100), maximum: Duration(seconds: 30), ); final socket = WebSocket( Uri.parse('ws://localhost:8080'), backoff: fibBackoff, ); print(fibBackoff.next()); // Duration(milliseconds: 100) print(fibBackoff.next()); // Duration(milliseconds: 100) print(fibBackoff.next()); // Duration(milliseconds: 200) print(fibBackoff.next()); // Duration(milliseconds: 300) print(fibBackoff.next()); // Duration(milliseconds: 500) } ``` -------------------------------- ### Send Message After WebSocket Connection Established in Dart Source: https://github.com/felangel/web_socket_client/blob/main/README.md Provides an example of sending a message to the WebSocket server only after confirming that the connection is established. It uses `firstWhere` to wait for the `Connected` state. ```dart final socket = WebSocket(Uri.parse('ws://localhost:8080')); // Wait until a connection has been established. await socket.connection.firstWhere((state) => state is Connected); // Send a message to the server. socket.send('ping'); ``` -------------------------------- ### Initialize WebSocket Client in Dart Source: https://context7.com/felangel/web_socket_client/llms.txt Demonstrates how to initialize the WebSocket client with various configurations including custom timeouts, backoff strategies, protocols, headers, and ping intervals. It also shows platform-specific binary type settings for web. ```dart import 'package:web_socket_client/web_socket_client.dart'; void main() { // Basic connection final socket = WebSocket(Uri.parse('ws://localhost:8080')); // With custom timeout and backoff strategy final socketWithConfig = WebSocket( Uri.parse('wss://example.com/ws'), timeout: Duration(seconds: 30), backoff: BinaryExponentialBackoff( initial: Duration(milliseconds: 100), maximumStep: 7, ), protocols: ['chat', 'superchat'], headers: {'Authorization': 'Bearer token123'}, pingInterval: Duration(seconds: 30), ); // For web platforms using Protobuf final protobufSocket = WebSocket( Uri.parse('wss://api.example.com/stream'), binaryType: 'arraybuffer', ); } ``` -------------------------------- ### Initialize and Use WebSocket Client in Dart Source: https://github.com/felangel/web_socket_client/blob/main/README.md Demonstrates the basic usage of the WebSocket client, including establishing a connection, listening for messages, sending messages, and closing the connection. This is the entry point for using the library. ```dart final socket = WebSocket(Uri.parse('ws://localhost:8080')); socket.messages.listen((message) { // Handle incoming messages. }); socket.send('ping'); socket.close(); ``` -------------------------------- ### Initialize WebSocket with Protobuf BinaryType on Web Source: https://github.com/felangel/web_socket_client/blob/main/README.md When using web_socket_client with Protobuf on the web, initialize the WebSocket class with the 'arraybuffer' binaryType. This setting is specific to web platforms and is not used on desktop or mobile. Consult MDN for more details on binaryType. ```dart final socket = WebSocket(Uri.parse('ws://localhost:8080'), binaryType: 'arraybuffer'); ``` -------------------------------- ### Receive WebSocket Messages in Dart Source: https://context7.com/felangel/web_socket_client/llms.txt Demonstrates how to listen for incoming messages on a WebSocket connection using the 'messages' broadcast stream. It includes handling JSON parsing and plain text messages, as well as supporting multiple concurrent listeners for processing data. ```dart import 'dart:convert'; import 'package:web_socket_client/web_socket_client.dart'; void main() { final socket = WebSocket(Uri.parse('ws://localhost:8080')); // Listen for incoming messages socket.messages.listen( (message) { try { // Try parsing as JSON final data = jsonDecode(message as String); print('Received JSON: ${data['type']} - ${data['content']}'); // Handle different message types switch (data['type']) { case 'notification': print('Notification: ${data['content']}'); case 'update': print('Update received: ${data['content']}'); case 'error': print('Server error: ${data['message']}'); } } catch (e) { // Handle plain text or binary messages print('Received message: $message'); } }, onError: (error) => print('Stream error: $error'), onDone: () => print('Message stream closed'), ); // Multiple listeners can subscribe socket.messages.listen((message) { // Logger or analytics handler print('[LOG] Message received at ${DateTime.now()}'); }); } ``` -------------------------------- ### Monitor WebSocket Connection State in Dart Source: https://github.com/felangel/web_socket_client/blob/main/README.md Shows how to monitor the WebSocket connection's state in real-time and query its current status. This allows for reacting to connection changes like connecting, connected, reconnecting, or disconnected. ```dart final uri = Uri.parse('ws://localhost:8080'); final socket = WebSocket(uri); // Listen to changes in the connection state. socket.connection.listen((state) { // Handle changes in the connection state. }); // Query the current connection state. final connectionState = socket.connection.state; ``` -------------------------------- ### Send Messages via WebSocket in Dart Source: https://context7.com/felangel/web_socket_client/llms.txt Illustrates how to send different types of data (text, JSON, binary) over a WebSocket connection using the `send` method. It includes waiting for the connection to be established before attempting to send messages. ```dart import 'dart:convert'; import 'package:web_socket_client/web_socket_client.dart'; void main() async { final socket = WebSocket(Uri.parse('ws://localhost:8080')); // Wait for connection await socket.connection.firstWhere((state) => state is Connected); // Send text message socket.send('Hello, Server!'); // Send JSON data final jsonData = jsonEncode({ 'type': 'chat_message', 'user': 'alice', 'message': 'Hello everyone!', 'timestamp': DateTime.now().toIso8601String(), }); socket.send(jsonData); // Send binary data final binaryData = [0x48, 0x65, 0x6c, 0x6c, 0x6f]; socket.send(binaryData); } ``` -------------------------------- ### Receive Messages from WebSocket Server in Dart Source: https://github.com/felangel/web_socket_client/blob/main/README.md Demonstrates how to listen for and handle incoming messages from the WebSocket server using the `messages` stream. This is crucial for receiving data from the server. ```dart final socket = WebSocket(Uri.parse('ws://localhost:8080')); // Listen for incoming messages. socket.messages.listen((message) { // Handle the incoming message. }); ``` -------------------------------- ### Configure Binary Exponential Backoff for WebSocket Reconnection in Dart Source: https://github.com/felangel/web_socket_client/blob/main/README.md Explains how to configure BinaryExponentialBackoff for WebSocket reconnections. This strategy doubles the waiting time between attempts until a maximum step is reached. ```dart // Initially wait 1s and double the wait time until a maximum step of of 3 is reached. // [1, 2, 4, 4, 4, ...] const backoff = BinaryExponentialBackoff( initial: Duration(seconds: 1), maximumStep: 3 ); final socket = WebSocket(uri, backoff: backoff); ``` -------------------------------- ### Binary Exponential Backoff Strategy for WebSocket Reconnection (Dart) Source: https://context7.com/felangel/web_socket_client/llms.txt Implements a binary exponential backoff strategy for WebSocket reconnections. This strategy doubles the wait time after each failed attempt until a maximum step count is reached, helping to reduce server load. It can be configured with an initial duration and a maximum step count. ```dart import 'package:web_socket_client/web_socket_client.dart'; void main() { // Start at 100ms, double each time, stop doubling after 7 steps // Pattern: [100ms, 200ms, 400ms, 800ms, 1600ms, 3200ms, 6400ms, 6400ms, ...] final backoff = BinaryExponentialBackoff( initial: Duration(milliseconds: 100), maximumStep: 7, ); final socket = WebSocket( Uri.parse('ws://localhost:8080'), backoff: backoff, ); // Default backoff used when none specified // BinaryExponentialBackoff(initial: 100ms, maximumStep: 7) final defaultSocket = WebSocket(Uri.parse('ws://localhost:8080')); // Manual usage example final testBackoff = BinaryExponentialBackoff( initial: Duration(seconds: 1), maximumStep: 4, ); print(testBackoff.next()); // Duration(seconds: 1) print(testBackoff.next()); // Duration(seconds: 2) print(testBackoff.next()); // Duration(seconds: 4) print(testBackoff.next()); // Duration(seconds: 8) print(testBackoff.next()); // Duration(seconds: 8) - reached maximum step testBackoff.reset(); print(testBackoff.next()); // Duration(seconds: 1) - back to initial } ``` -------------------------------- ### Configure WebSocket Connection Timeout in Dart Source: https://github.com/felangel/web_socket_client/blob/main/README.md Shows how to set a custom timeout duration for establishing the WebSocket connection. If the connection cannot be established within the specified duration, it will fail. ```dart final uri = Uri.parse('ws://localhost:8080'); // Trigger a timeout if establishing a connection exceeds 10s. final timeout = Duration(seconds: 10); final socket = WebSocket(uri, timeout: timeout); ``` -------------------------------- ### Implement Constant Backoff Strategy in Dart Source: https://context7.com/felangel/web_socket_client/llms.txt Shows how to use the ConstantBackoff strategy for WebSocket reconnections. This strategy maintains a fixed delay between retry attempts, ensuring consistent intervals regardless of connection failures. It can also be used manually to retrieve backoff durations. ```dart import 'package:web_socket_client/web_socket_client.dart'; void main() { // Wait 2 seconds between each reconnection attempt // Pattern: [2s, 2s, 2s, 2s, ...] const backoff = ConstantBackoff(Duration(seconds: 2)); final socket = WebSocket( Uri.parse('ws://localhost:8080'), backoff: backoff, timeout: Duration(seconds: 60), ); socket.connection.listen((state) { if (state is Reconnecting) { print('Reconnecting in 2 seconds...'); } }); // Manual usage example final customBackoff = ConstantBackoff(Duration(milliseconds: 500)); print(customBackoff.next()); // Duration(milliseconds: 500) print(customBackoff.next()); // Duration(milliseconds: 500) print(customBackoff.next()); // Duration(milliseconds: 500) } ``` -------------------------------- ### Dart WebSocket Client with Connection Management and Messaging Source: https://context7.com/felangel/web_socket_client/llms.txt This Dart code implements a WebSocket client for a chat application. It manages connection states, handles incoming JSON messages, sends chat messages, and supports graceful disconnection with automatic reconnection. It uses the 'web_socket_client' package for WebSocket communication and 'dart:convert' for JSON parsing. ```dart import 'dart:async'; import 'dart:convert'; import 'package:web_socket_client/web_socket_client.dart'; class ChatClient { ChatClient(this.serverUrl, this.username); final String serverUrl; final String username; late WebSocket _socket; void connect() { _socket = WebSocket( Uri.parse(serverUrl), backoff: BinaryExponentialBackoff( initial: Duration(milliseconds: 500), maximumStep: 5, ), timeout: Duration(seconds: 30), headers: {'User-Agent': 'ChatClient/1.0'}, ); // Monitor connection state _socket.connection.listen((state) { switch (state) { case Connecting(): print('[$username] Connecting to chat server...'); case Connected(): print('[$username] Connected! Joining chat...'); _sendMessage('join', {'username': username}); case Reconnecting(): print('[$username] Connection lost, reconnecting...'); case Reconnected(): print('[$username] Reconnected! Rejoining chat...'); _sendMessage('rejoin', {'username': username}); case Disconnecting(): print('[$username] Leaving chat...'); case Disconnected(:final code, :final reason, :final error): if (error != null) { print('[$username] Disconnected due to error: $error'); } else { print('[$username] Disconnected: $code - $reason'); } } }); // Handle incoming messages _socket.messages.listen( (rawMessage) { try { final message = jsonDecode(rawMessage as String); _handleMessage(message); } catch (e) { print('[$username] Failed to parse message: $e'); } }, onError: (error) => print('[$username] Message stream error: $error'), ); } void _handleMessage(Map message) { final type = message['type']; switch (type) { case 'chat': print('[${message['user']}]: ${message['text']}'); case 'user_joined': print('*** ${message['user']} joined the chat'); case 'user_left': print('*** ${message['user']} left the chat'); case 'system': print('*** SYSTEM: ${message['text']}'); default: print('[$username] Unknown message type: $type'); } } void _sendMessage(String type, Map data) { final message = jsonEncode({ 'type': type, ...data, 'timestamp': DateTime.now().toIso8601String(), }); _socket.send(message); } Future sendChat(String text) async { // Ensure connected before sending await _socket.connection.firstWhere((state) => state is Connected || state is Reconnected); _sendMessage('chat', {'user': username, 'text': text}); } void disconnect() { _sendMessage('leave', {'username': username}); _socket.close(1000, 'User logout'); } String get protocol => _socket.protocol; } void main() async { final client = ChatClient('ws://localhost:8080/chat', 'Alice'); client.connect(); // Wait for connection await Future.delayed(Duration(seconds: 2)); // Send messages await client.sendChat('Hello everyone!'); await client.sendChat('How is everyone doing?'); // Stay connected for 10 seconds await Future.delayed(Duration(seconds: 10)); // Graceful disconnect client.disconnect(); // Wait for disconnection to complete await Future.delayed(Duration(seconds: 1)); print('Chat session ended'); } ``` -------------------------------- ### Configure Linear Backoff for WebSocket Reconnection in Dart Source: https://github.com/felangel/web_socket_client/blob/main/README.md Demonstrates the use of LinearBackoff for WebSocket reconnections. This strategy increases the waiting time linearly between attempts up to a specified maximum duration. ```dart // Initially wait 0s and increase the wait time by 1s until a maximum of 5s is reached. // [0, 1, 2, 3, 4, 5, 5, 5, ...] const backoff = LinearBackoff( initial: Duration(seconds: 0), increment: Duration(seconds: 1), maximum: Duration(seconds: 5), ); final socket = WebSocket(uri, backoff: backoff); ``` -------------------------------- ### Closing WebSocket Connection Gracefully (Dart) Source: https://context7.com/felangel/web_socket_client/llms.txt Demonstrates how to properly close a WebSocket connection using the `close` method. This initiates a closing handshake with the server and cleans up resources. After closing, the client will not automatically reconnect, requiring a new instance for subsequent connections. The `close` method can optionally take a status code and reason. ```dart import 'package:web_socket_client/web_socket_client.dart'; void main() async { final socket = WebSocket(Uri.parse('ws://localhost:8080')); await socket.connection.firstWhere((state) => state is Connected); // Send some messages socket.send('message 1'); socket.send('message 2'); // Wait for processing await Future.delayed(Duration(seconds: 2)); // Close with standard code and reason socket.close(1000, 'Normal closure'); // Wait for disconnection await socket.connection.firstWhere((state) => state is Disconnected); print('Connection closed successfully'); // Alternative: close without code/reason final anotherSocket = WebSocket(Uri.parse('ws://localhost:8080')); await Future.delayed(Duration(seconds: 5)); anotherSocket.close(); } ``` -------------------------------- ### Configure Constant Backoff for WebSocket Reconnection in Dart Source: https://github.com/felangel/web_socket_client/blob/main/README.md Illustrates how to configure a ConstantBackoff strategy for automatic WebSocket reconnections. This strategy waits a fixed amount of time between each reconnection attempt. ```dart // Wait a constant 1s between reconnection attempts. // [1, 1, 1, ...] const backoff = ConstantBackoff(Duration(seconds: 1)); final socket = WebSocket(uri, backoff: backoff); ``` -------------------------------- ### Close WebSocket Connection Source: https://github.com/felangel/web_socket_client/blob/main/README.md To close an established WebSocket connection, call the close() method on the WebSocket instance. This initiates the closing handshake, updates the connection state to 'disconnecting', and finally to 'disconnected'. After closing, the client will not attempt to reconnect, requiring a new instance for a new connection. ```dart final socket = WebSocket(Uri.parse('ws://localhost:8080')); // Later, close the connection with an optional code and reason. socket.close(1000, 'CLOSE_NORMAL'); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.