WebSockets en Flutter: ejercicio resuelto con web_socket_channel

WebSockets en Flutter: ejercicio resuelto con web_socket_channel

Los WebSockets permiten comunicación bidireccional y persistente entre cliente y servidor. A diferencia de HTTP, el servidor puede enviar datos sin que el cliente los pida. Son ideales para chats, feeds de precios, notificaciones en vivo y juegos multijugador.

Enunciado

Implementa un ticker de precios en tiempo real que:

  • Se conecta a un servidor WebSocket.
  • Muestra actualizaciones de precios con StreamBuilder.
  • Permite suscribirse y desuscribirse a símbolos (BTC, ETH, SOL).
  • Gestiona reconexión automática con backoff exponencial.
  • Muestra estado de conexión (conectando, conectado, desconectado, error).

Dependencias

1
2
3
4
5
# pubspec.yaml
dependencies:
  flutter:
    sdk: flutter
  web_socket_channel: ^3.0.1

Solución completa

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
import 'dart:async';
import 'dart:convert';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

void main() => runApp(const MaterialApp(home: PriceTicker()));

// ── Modelos ────────────────────────────────────────────────────────────────────
enum ConnectionState { connecting, connected, disconnected, error }

class PriceUpdate {
  final String symbol;
  final double price;
  final double change;  // cambio porcentual respecto al precio anterior
  final DateTime timestamp;

  PriceUpdate({
    required this.symbol,
    required this.price,
    required this.change,
    required this.timestamp,
  });

  factory PriceUpdate.fromJson(Map<String, dynamic> json) => PriceUpdate(
        symbol: json['symbol'] as String,
        price: (json['price'] as num).toDouble(),
        change: (json['change'] as num).toDouble(),
        timestamp: DateTime.parse(json['ts'] as String),
      );
}

// ── Servicio WebSocket con reconexión ──────────────────────────────────────────
class PriceWebSocketService {
  // Para pruebas reales puedes usar wss://stream.binance.com:9443/ws
  // Aquí usamos un echo server público y simulamos datos localmente
  static const _wsUrl = 'wss://echo.websocket.org';

  WebSocketChannel? _channel;
  StreamController<PriceUpdate>? _priceController;
  Timer? _reconnectTimer;
  Timer? _simulatorTimer;
  int _retryCount = 0;
  bool _disposed = false;

  // Estado de conexión expuesto como ValueNotifier
  final connectionState = ValueNotifier(ConnectionState.disconnected);

  Stream<PriceUpdate> get priceStream =>
      (_priceController ??= StreamController.broadcast()).stream;

  final _subscriptions = <String>{};
  final _prices = <String, double>{'BTC': 65000, 'ETH': 3200, 'SOL': 145};

  void connect() {
    if (_disposed) return;
    _priceController ??= StreamController.broadcast();
    connectionState.value = ConnectionState.connecting;

    try {
      _channel = WebSocketChannel.connect(Uri.parse(_wsUrl));
      _channel!.ready.then((_) {
        if (_disposed) return;
        connectionState.value = ConnectionState.connected;
        _retryCount = 0;
        // Reenviar suscripciones activas
        for (final symbol in _subscriptions) {
          _sendSubscribe(symbol);
        }
        // En un servidor real, escucharíamos _channel!.stream
        // Aquí simulamos actualizaciones localmente para el ejemplo
        _startSimulator();
      }).catchError(_handleError);
    } catch (e) {
      _handleError(e);
    }
  }

  void subscribe(String symbol) {
    _subscriptions.add(symbol);
    if (connectionState.value == ConnectionState.connected) {
      _sendSubscribe(symbol);
    }
  }

  void unsubscribe(String symbol) {
    _subscriptions.remove(symbol);
    if (connectionState.value == ConnectionState.connected) {
      _channel?.sink.add(jsonEncode({'action': 'unsubscribe', 'symbol': symbol}));
    }
  }

  void _sendSubscribe(String symbol) {
    _channel?.sink.add(jsonEncode({'action': 'subscribe', 'symbol': symbol}));
  }

  void _startSimulator() {
    _simulatorTimer?.cancel();
    final rng = Random();
    _simulatorTimer = Timer.periodic(const Duration(seconds: 1), (_) {
      for (final symbol in _subscriptions) {
        final prev = _prices[symbol]!;
        final delta = (rng.nextDouble() - 0.49) * prev * 0.005;
        final newPrice = prev + delta;
        _prices[symbol] = newPrice;
        _priceController?.add(PriceUpdate(
          symbol: symbol,
          price: newPrice,
          change: delta / prev * 100,
          timestamp: DateTime.now(),
        ));
      }
    });
  }

  void _handleError(dynamic error) {
    if (_disposed) return;
    connectionState.value = ConnectionState.error;
    _simulatorTimer?.cancel();
    _scheduleReconnect();
  }

  void _scheduleReconnect() {
    _reconnectTimer?.cancel();
    final delay = Duration(seconds: min(30, pow(2, _retryCount).toInt()));
    _retryCount++;
    _reconnectTimer = Timer(delay, connect);
  }

  void disconnect() {
    _reconnectTimer?.cancel();
    _simulatorTimer?.cancel();
    _channel?.sink.close();
    connectionState.value = ConnectionState.disconnected;
  }

  void dispose() {
    _disposed = true;
    disconnect();
    _priceController?.close();
  }
}

// ── Pantalla principal ─────────────────────────────────────────────────────────
class PriceTicker extends StatefulWidget {
  const PriceTicker({super.key});
  @override
  State<PriceTicker> createState() => _PriceTickerState();
}

class _PriceTickerState extends State<PriceTicker> {
  final _service = PriceWebSocketService();
  final _latestPrices = <String, PriceUpdate>{};
  StreamSubscription<PriceUpdate>? _sub;

  @override
  void initState() {
    super.initState();
    _service.connect();
    // Suscribirse a los tres símbolos por defecto
    for (final s in ['BTC', 'ETH', 'SOL']) {
      _service.subscribe(s);
    }
    _sub = _service.priceStream.listen((update) {
      if (mounted) setState(() => _latestPrices[update.symbol] = update);
    });
  }

  @override
  void dispose() {
    _sub?.cancel();
    _service.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Ticker en tiempo real'),
        actions: [
          ValueListenableBuilder(
            valueListenable: _service.connectionState,
            builder: (_, state, __) => Padding(
              padding: const EdgeInsets.only(right: 16),
              child: _ConnectionBadge(state: state),
            ),
          ),
        ],
      ),
      body: Column(
        children: [
          // Lista de precios
          Expanded(
            child: _latestPrices.isEmpty
                ? const Center(child: CircularProgressIndicator())
                : ListView(
                    padding: const EdgeInsets.all(12),
                    children: _latestPrices.values
                        .map((u) => _PriceCard(update: u))
                        .toList(),
                  ),
          ),
          // Panel de suscripciones
          _SubscriptionPanel(service: _service),
        ],
      ),
    );
  }
}

// ── Widgets ────────────────────────────────────────────────────────────────────
class _ConnectionBadge extends StatelessWidget {
  final ConnectionState state;
  const _ConnectionBadge({required this.state});

  @override
  Widget build(BuildContext context) {
    final (label, color) = switch (state) {
      ConnectionState.connected => ('● Conectado', Colors.green),
      ConnectionState.connecting => ('● Conectando…', Colors.orange),
      ConnectionState.error => ('● Error', Colors.red),
      ConnectionState.disconnected => ('● Desconectado', Colors.grey),
    };
    return Text(label, style: TextStyle(color: color, fontSize: 12));
  }
}

class _PriceCard extends StatelessWidget {
  final PriceUpdate update;
  const _PriceCard({required this.update});

  @override
  Widget build(BuildContext context) {
    final isUp = update.change >= 0;
    return Card(
      child: ListTile(
        leading: CircleAvatar(child: Text(update.symbol[0])),
        title: Text(update.symbol,
            style: const TextStyle(fontWeight: FontWeight.bold)),
        subtitle: Text(
            '${TimeOfDay.fromDateTime(update.timestamp).format(context)}'),
        trailing: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Text(
              '\$${update.price.toStringAsFixed(2)}',
              style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            Text(
              '${isUp ? '+' : ''}${update.change.toStringAsFixed(3)}%',
              style: TextStyle(
                  color: isUp ? Colors.green : Colors.red, fontSize: 12),
            ),
          ],
        ),
      ),
    );
  }
}

class _SubscriptionPanel extends StatefulWidget {
  final PriceWebSocketService service;
  const _SubscriptionPanel({required this.service});
  @override
  State<_SubscriptionPanel> createState() => _SubscriptionPanelState();
}

class _SubscriptionPanelState extends State<_SubscriptionPanel> {
  final _active = {'BTC', 'ETH', 'SOL'};
  static const _available = ['BTC', 'ETH', 'SOL', 'ADA', 'DOT', 'AVAX'];

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        border: Border(top: BorderSide(color: Colors.grey.shade300)),
      ),
      child: Wrap(
        spacing: 8,
        children: _available.map((symbol) {
          final isActive = _active.contains(symbol);
          return FilterChip(
            label: Text(symbol),
            selected: isActive,
            onSelected: (selected) {
              setState(() {
                if (selected) {
                  _active.add(symbol);
                  widget.service.subscribe(symbol);
                } else {
                  _active.remove(symbol);
                  widget.service.unsubscribe(symbol);
                }
              });
            },
          );
        }).toList(),
      ),
    );
  }
}

Reconexión con backoff exponencial

1
2
3
4
5
6
void _scheduleReconnect() {
  // Espera 1s, 2s, 4s, 8s… hasta máximo 30s
  final delay = Duration(seconds: min(30, pow(2, _retryCount).toInt()));
  _retryCount++;
  _reconnectTimer = Timer(delay, connect);
}

El backoff exponencial evita saturar el servidor con reconexiones inmediatas cuando hay un fallo sostenido.

Errores frecuentes

  • No cerrar el sink al desmontar el widget: causa memory leaks. Llama siempre a channel.sink.close() en dispose().
  • StreamSubscription sin cancelar: igual que con cualquier Stream, cancela la suscripción en dispose.
  • WebSocket seguro en producción: usa wss:// (TLS) en producción. ws:// texto plano no es aceptable para datos sensibles.

Aplicación práctica

WebSockets se usan en: chats (WhatsApp Web, Slack), feeds financieros (Binance, Coinbase), dashboards en tiempo real, juegos multijugador, colaboración en tiempo real (Google Docs, Figma).

Siguiente ejercicio recomendado

Práctica guiada y siguiente paso

FAQ

¿Puedo usar WebSockets con Riverpod o BLoC?

Sí. Convierte el Stream del canal en un StreamProvider de Riverpod o en un Stream que tu BLoC escucha con on<Event>. El canal WebSocket vive en el repositorio, fuera del BLoC.

¿Qué diferencia hay entre WebSocket y Server-Sent Events (SSE)?

SSE es unidireccional (servidor → cliente), basado en HTTP, más simple. WebSocket es bidireccional, más eficiente para comunicación frecuente en ambas direcciones. Usa SSE para feeds de noticias o precios de solo lectura; WebSocket para chat o juegos.

¿Cómo manejo autenticación en WebSockets?

Envía el token en la cabecera de la petición de upgrade o como primer mensaje tras conectar. Muchos servidores aceptan el token como query param (?token=...) en la URL del WebSocket.