flutter_websocket_plus 0.0.1
flutter_websocket_plus: ^0.0.1 copied to clipboard
WebSocket connection management with reconnection logic and message queuing. Supports all 6 platforms with WASM compatibility.
flutter_websocket_plus #
A powerful and feature-rich WebSocket package for Flutter with automatic reconnection, message queuing, and cross-platform support.
Features #
π Cross-Platform Support: Works on all 6 platforms (iOS, Android, Web, Windows, macOS, Linux)
π Automatic Reconnection: Smart reconnection strategies with exponential backoff
π¬ Message Queuing: Reliable message delivery with priority queuing
π Heartbeat Support: Built-in ping/pong for connection health monitoring
β‘ High Performance: Optimized for real-time applications
π‘οΈ Error Handling: Comprehensive error handling and recovery
π Statistics & Monitoring: Detailed connection and queue statistics
π§ Configurable: Highly customizable connection parameters
π WASM Compatible: Full support for web platform including WASM
Getting Started #
Installation #
Add this to your package's pubspec.yaml
file:
dependencies:
flutter_websocket_plus: ^0.0.1
Basic Usage #
import 'package:flutter_websocket_plus/flutter_websocket_plus.dart';
// Create configuration
final config = WebSocketConfig(
url: 'wss://echo.websocket.org',
enableReconnection: true,
enableMessageQueue: true,
);
// Create manager
final manager = WebSocketManager(config: config);
// Connect to WebSocket server
await manager.connect();
// Send messages
await manager.sendText('Hello, WebSocket!');
await manager.sendJson({'type': 'message', 'content': 'Hello'});
// Listen to messages
manager.messageStream.listen((message) {
print('Received: ${message.data}');
});
// Listen to connection state changes
manager.stateStream.listen((state) {
print('Connection state: ${state.connectionState}');
});
Advanced Usage #
Custom Reconnection Strategy #
// Create custom reconnection strategy
final strategy = ExponentialBackoffStrategy(
initialDelay: Duration(seconds: 1),
maxDelay: Duration(minutes: 5),
multiplier: 2.0,
);
// Use with manager
final manager = WebSocketManager(
config: config,
reconnectionStrategy: strategy,
);
Message Queuing #
// Create message with acknowledgment requirement
final message = WebSocketMessage.json(
{'type': 'important', 'data': 'critical info'},
requiresAck: true,
);
// Send message (will be queued if connection is down)
await manager.send(message);
Configuration Options #
final config = WebSocketConfig(
url: 'wss://your-server.com',
connectionTimeout: Duration(seconds: 30),
enableReconnection: true,
maxReconnectionAttempts: 10,
initialReconnectionDelay: Duration(seconds: 1),
maxReconnectionDelay: Duration(minutes: 5),
enableMessageQueue: true,
maxQueueSize: 1000,
heartbeatInterval: Duration(seconds: 30),
enableHeartbeat: true,
headers: {'Authorization': 'Bearer token'},
protocols: ['protocol1', 'protocol2'],
);
Event Handling #
// Listen to all events
manager.eventStream.listen((event) {
switch (event.type) {
case 'connected':
print('Connected to WebSocket server');
break;
case 'disconnected':
print('Disconnected from WebSocket server');
break;
case 'reconnecting':
print('Reconnecting... Attempt ${event.data}');
break;
case 'messageSent':
print('Message sent: ${event.data}');
break;
case 'messageQueued':
print('Message queued: ${event.data}');
break;
case 'error':
print('Error: ${event.data}');
break;
}
});
Statistics and Monitoring #
// Get connection statistics
final stats = manager.statistics;
print('Connection state: ${stats['connectionState']}');
print('Queue size: ${stats['queueStatistics']['size']}');
print('Reconnection attempts: ${stats['reconnectionAttempt']}');
// Get queue statistics
final queueStats = manager.queueStatistics;
print('Queue size: ${queueStats['size']}');
print('Retryable messages: ${queueStats['retryableCount']}');
Platform Support #
Platform | Support | Notes |
---|---|---|
iOS | β Full | Native WebSocket implementation |
Android | β Full | Native WebSocket implementation |
Web | β Full | Browser WebSocket + WASM compatible |
Windows | β Full | Native WebSocket implementation |
macOS | β Full | Native WebSocket implementation |
Linux | β Full | Native WebSocket implementation |
Architecture #
The package is built with a layered architecture:
- WebSocketManager: High-level manager with reconnection and queuing
- WebSocketConnection: Low-level connection management
- MessageQueue: Priority-based message queuing system
- ReconnectionStrategy: Pluggable reconnection algorithms
- WebSocketMessage: Rich message representation with metadata
Reconnection Strategies #
Exponential Backoff (Default) #
- Starts with initial delay and exponentially increases
- Includes randomization to prevent thundering herd
- Configurable maximum delay cap
Linear Backoff #
- Linear increase in delay between attempts
- Predictable reconnection timing
- Good for controlled environments
Fixed Delay #
- Constant delay between reconnection attempts
- Simple and predictable
- Suitable for stable networks
No Reconnection #
- Disables automatic reconnection
- Useful for testing or manual control
Message Types #
- Text: Plain text messages
- Binary: Binary data (bytes)
- JSON: Structured JSON data
- Ping/Pong: Heartbeat control messages
Error Handling #
The package provides comprehensive error handling:
- Connection failures with automatic retry
- Message sending failures with queuing
- Network timeouts with configurable limits
- Graceful degradation when features are disabled
Performance Considerations #
- Efficient message queuing with O(log n) priority operations
- Minimal memory overhead for connection management
- Optimized reconnection timing algorithms
- Lazy initialization of resources
Testing #
# Run all tests
flutter test
# Run tests with coverage
flutter test --coverage
# Run specific test file
flutter test test/websocket_manager_test.dart
Contributing #
Contributions are welcome! Please feel free to submit a Pull Request.
License #
This project is licensed under the MIT License - see the LICENSE file for details.
Support #
If you encounter any issues or have questions, please:
- Check the documentation
- Search existing issues
- Create a new issue
Changelog #
See CHANGELOG.md for a detailed list of changes.
Made with β€οΈ by Dhia-Bechattaoui