51 lines
1.4 KiB
Dart
51 lines
1.4 KiB
Dart
import 'dart:async';
|
|
import 'dart:io';
|
|
import 'dart:typed_data';
|
|
|
|
import 'package:web_socket_channel/io.dart';
|
|
import 'package:web_socket_channel/web_socket_channel.dart';
|
|
|
|
import 'websocket_transport_base.dart';
|
|
|
|
/// Native (Linux + Android) WebSocket transport using IOWebSocketChannel.
|
|
class WebSocketTransport extends WebSocketTransportBase {
|
|
WebSocketTransport({
|
|
super.initialReconnectDelay,
|
|
super.maxReconnectDelay,
|
|
super.backoffFactor,
|
|
});
|
|
|
|
WebSocketChannel? _channel;
|
|
StreamSubscription<dynamic>? _sub;
|
|
|
|
@override
|
|
Future<void> openPlatform(String url) async {
|
|
_channel = IOWebSocketChannel.connect(
|
|
Uri.parse(url),
|
|
pingInterval: const Duration(seconds: 10),
|
|
);
|
|
// Awaiting `ready` surfaces connection failures as exceptions.
|
|
await _channel!.ready;
|
|
_sub = _channel!.stream.listen(
|
|
(dynamic message) {
|
|
if (message is Uint8List) {
|
|
onBytes(message);
|
|
} else if (message is List<int>) {
|
|
onBytes(Uint8List.fromList(message));
|
|
}
|
|
// String messages are ignored — server should send binary protobuf.
|
|
},
|
|
onError: (_) => onChannelClosed(),
|
|
onDone: onChannelClosed,
|
|
cancelOnError: true,
|
|
);
|
|
}
|
|
|
|
@override
|
|
Future<void> closePlatform() async {
|
|
await _sub?.cancel();
|
|
_sub = null;
|
|
await _channel?.sink.close(WebSocketStatus.normalClosure);
|
|
_channel = null;
|
|
}
|
|
} |