import 'dart:async'; import 'package:bonsoir/bonsoir.dart'; import 'discovered_server.dart'; import 'server_discovery.dart'; /// DNS-SD browsing through the platform service: Android NSD (Bonsoir holds /// the Wi-Fi multicast lock while browsing) and Apple's Network framework /// (needs NSLocalNetworkUsageDescription and NSBonjourServices). class BonsoirServerDiscovery implements ServerDiscovery { BonsoirServerDiscovery({this.type = pipelinesServiceType}); final String type; @override Stream> scan() { late final StreamController> controller; BonsoirDiscovery? discovery; StreamSubscription? events; final found = {}; void publish() { if (!controller.isClosed) controller.add(found.values.toList()); } Future start() async { try { final browser = BonsoirDiscovery(type: type); discovery = browser; await browser.initialize(); if (controller.isClosed) return; events = browser.eventStream?.listen( (event) { switch (event) { case BonsoirDiscoveryServiceFoundEvent(:final service): unawaited(service.resolve(browser.serviceResolver)); case BonsoirDiscoveryServiceResolvedEvent(:final service) || BonsoirDiscoveryServiceUpdatedEvent(:final service): final server = DiscoveredServer.fromRecord( instance: service.name, addresses: service.hostAddresses, hostname: service.hostname, port: service.port, attributes: service.attributes, ); if (server != null) { found[service.name] = server; publish(); } case BonsoirDiscoveryServiceLostEvent(:final service): if (found.remove(service.name) != null) publish(); default: break; } }, onError: (Object error) { if (!controller.isClosed) controller.addError(error); }, ); await browser.start(); publish(); } catch (error, stack) { if (!controller.isClosed) controller.addError(error, stack); } } controller = StreamController>( onListen: () => unawaited(start()), onCancel: () async { await events?.cancel(); final browser = discovery; if (browser != null && !browser.isStopped) { try { await browser.stop(); } catch (_) { // Already stopped by the platform; nothing else to release. } } await controller.close(); }, ); return controller.stream; } }