forked from flutter/packages
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlookup_resolver.dart
More file actions
83 lines (70 loc) · 2.51 KB
/
lookup_resolver.dart
File metadata and controls
83 lines (70 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Copyright (c) 2015, the Dartino project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:collection';
import 'package:multicast_dns/src/resource_record.dart';
/// Class for maintaining state about pending mDNS requests.
class PendingRequest extends LinkedListEntry<PendingRequest> {
/// Creates a new PendingRequest.
PendingRequest(this.type, this.name, this.controller);
/// The [RRType] of the request.
final int type;
/// The domain name.
final String name;
/// A StreamController managing the request.
final StreamController<ResourceRecord> controller;
/// The timer for the request.
Timer timer;
}
/// Class for keeping track of pending lookups and process incoming
/// query responses.
class LookupResolver {
/// The requests the process.
final LinkedList<PendingRequest> pendingRequests =
LinkedList<PendingRequest>();
/// Adds a request and returns a [Stream] of [ResourceRecord] responses.
Stream<ResourceRecord> addPendingRequest(
int type, String name, Duration timeout) {
final StreamController<ResourceRecord> controller =
StreamController<ResourceRecord>();
final PendingRequest request = PendingRequest(type, name, controller);
final Timer timer = Timer(timeout, () {
request.unlink();
controller.close();
});
request.timer = timer;
pendingRequests.add(request);
return controller.stream;
}
/// Processes responses back to the caller.
void handleResponse(List<ResourceRecord> response) {
for (ResourceRecord r in response) {
final int type = r.rrValue;
String name = r.name.toLowerCase();
if (name.endsWith('.')) {
name = name.substring(0, name.length - 1);
}
bool responseMatches(PendingRequest request) {
return request.name.toLowerCase() == name && request.type == type;
}
for (PendingRequest pendingRequest in pendingRequests) {
if (responseMatches(pendingRequest)) {
if (pendingRequest.controller.isClosed) {
return;
}
pendingRequest.controller.add(r);
}
}
}
}
/// Removes any pending requests and ends processing.
void clearPendingRequests() {
while (pendingRequests.isNotEmpty) {
final PendingRequest request = pendingRequests.first;
request.unlink();
request.timer.cancel();
request.controller.close();
}
}
}