flutter_websocket_plus

Pub Version License Flutter Dart

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:

  1. Check the documentation
  2. Search existing issues
  3. Create a new issue

Changelog

See CHANGELOG.md for a detailed list of changes.


Made with ❀️ by Dhia-Bechattaoui