51 lines
1.1 KiB
Dart
51 lines
1.1 KiB
Dart
import 'dart:async';
|
|
import 'package:nsd/nsd.dart';
|
|
|
|
abstract class IDiscoveryService {
|
|
Future<void> registerService(int port);
|
|
Future<void> stopRegistration();
|
|
Stream<List<Service>> discoverServices();
|
|
}
|
|
|
|
class DiscoveryService implements IDiscoveryService {
|
|
Registration? _registration;
|
|
final String _serviceType = '_http._tcp';
|
|
final String _serviceName = 'FastWatcher';
|
|
|
|
@override
|
|
Future<void> registerService(int port) async {
|
|
_registration = await register(
|
|
Service(
|
|
name: _serviceName,
|
|
type: _serviceType,
|
|
port: port,
|
|
),
|
|
);
|
|
}
|
|
|
|
@override
|
|
Future<void> stopRegistration() async {
|
|
if (_registration != null) {
|
|
await unregister(_registration!);
|
|
_registration = null;
|
|
}
|
|
}
|
|
|
|
@override
|
|
Stream<List<Service>> discoverServices() async* {
|
|
final discovery = await startDiscovery(_serviceType);
|
|
final controller = StreamController<List<Service>>();
|
|
|
|
void update() {
|
|
controller.add(discovery.services);
|
|
}
|
|
|
|
discovery.addListener(update);
|
|
|
|
yield* controller.stream;
|
|
|
|
// Note: In a real app, handle disposal
|
|
}
|
|
}
|
|
|