@@ -175,26 +175,36 @@ Future<String> _searchMdns(String address) async {
175
175
const type = '_rpc._tcp' ;
176
176
final discovery = BonsoirDiscovery (type: type);
177
177
await discovery.ready;
178
- await discovery.start ();
179
178
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) {
189
181
if (event.type == BonsoirDiscoveryEventType .discoveryServiceFound) {
190
182
unawaited (event.service! .resolve (discovery.serviceResolver));
191
183
} else if (event.type == BonsoirDiscoveryEventType .discoveryServiceResolved) {
192
184
final service = event.service! as ResolvedBonsoirService ;
193
185
if (service.name == targetName && service.host != null ) {
194
186
final host = service.host! .substring (0 , service.host! .length - 1 );
195
- return ( '$host :${service .port }' ) ;
187
+ localAddress = '$host :${service .port }' ;
196
188
}
197
189
}
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
+ }
198
208
}
199
209
200
210
await discovery.stop ();
0 commit comments