Skip to content

Commit 36c087c

Browse files
authored
Start mdns after setting listeners (#312)
1 parent 6cc4426 commit 36c087c

File tree

1 file changed

+21
-11
lines changed

1 file changed

+21
-11
lines changed

lib/src/rpc/dial.dart

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -175,26 +175,36 @@ Future<String> _searchMdns(String address) async {
175175
const type = '_rpc._tcp';
176176
final discovery = BonsoirDiscovery(type: type);
177177
await discovery.ready;
178-
await discovery.start();
179178

180-
// The duration of timeout was arbitrarily decided.
181-
// 1 second seemed enough to allow the device to scan
182-
// the local network for matches before moving on.
183-
// The balance we are striking here is long enough to
184-
// reliably scan the local network, but short enough to not
185-
// noticeably lengthen the connection flow for the user.
186-
187-
const timeout = Duration(seconds: 1);
188-
await for (final event in discovery.eventStream!.timeout(timeout)) {
179+
String? localAddress;
180+
discovery.eventStream!.listen((event) {
189181
if (event.type == BonsoirDiscoveryEventType.discoveryServiceFound) {
190182
unawaited(event.service!.resolve(discovery.serviceResolver));
191183
} else if (event.type == BonsoirDiscoveryEventType.discoveryServiceResolved) {
192184
final service = event.service! as ResolvedBonsoirService;
193185
if (service.name == targetName && service.host != null) {
194186
final host = service.host!.substring(0, service.host!.length - 1);
195-
return ('$host:${service.port}');
187+
localAddress = '$host:${service.port}';
196188
}
197189
}
190+
});
191+
192+
await discovery.start();
193+
final startTime = DateTime.now();
194+
195+
// The duration of timeout was arbitrarily decided.
196+
// 2 seconds seemed enough to allow the device to scan
197+
// the local network for matches before moving on.
198+
// The balance we are striking here is long enough to
199+
// reliably scan the local network, but short enough to not
200+
// noticeably lengthen the connection flow for the user.
201+
const timeout = Duration(seconds: 2);
202+
while (DateTime.now().difference(startTime) < timeout) {
203+
await Future.delayed(const Duration(microseconds: 100));
204+
if (localAddress != null) {
205+
await discovery.stop();
206+
return localAddress!;
207+
}
198208
}
199209

200210
await discovery.stop();

0 commit comments

Comments
 (0)