OLD | NEW |
1 // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file | 1 // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file |
2 // for details. All rights reserved. Use of this source code is governed by a | 2 // for details. All rights reserved. Use of this source code is governed by a |
3 // BSD-style license that can be found in the LICENSE file. | 3 // BSD-style license that can be found in the LICENSE file. |
4 | 4 |
5 library test.util.io; | 5 library test.util.io; |
6 | 6 |
7 import 'dart:async'; | 7 import 'dart:async'; |
8 import 'dart:convert'; | 8 import 'dart:convert'; |
9 import 'dart:io'; | 9 import 'dart:io'; |
10 import 'dart:mirrors'; | 10 import 'dart:mirrors'; |
(...skipping 190 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
201 /// | 201 /// |
202 /// [tryPort] should return a non-`null` value or a Future completing to a | 202 /// [tryPort] should return a non-`null` value or a Future completing to a |
203 /// non-`null` value once it binds successfully. This value will be returned | 203 /// non-`null` value once it binds successfully. This value will be returned |
204 /// by [getUnusedPort] in turn. | 204 /// by [getUnusedPort] in turn. |
205 /// | 205 /// |
206 /// This is necessary for ensuring that our port binding isn't flaky for | 206 /// This is necessary for ensuring that our port binding isn't flaky for |
207 /// applications that don't print out the bound port. | 207 /// applications that don't print out the bound port. |
208 Future getUnusedPort(tryPort(int port)) { | 208 Future getUnusedPort(tryPort(int port)) { |
209 var value; | 209 var value; |
210 return Future.doWhile(() async { | 210 return Future.doWhile(() async { |
211 var socket = await RawServerSocket.bind(InternetAddress.LOOPBACK_IP_V4, 0); | 211 value = await tryPort(await getUnsafeUnusedPort()); |
212 var port = socket.port; | |
213 await socket.close(); | |
214 | |
215 value = await tryPort(port); | |
216 return value == null; | 212 return value == null; |
217 }).then((_) => value); | 213 }).then((_) => value); |
218 } | 214 } |
| 215 |
| 216 /// Returns a port that is probably, but not definitely, not in use. |
| 217 /// |
| 218 /// This has a built-in race condition: another process may bind this port at |
| 219 /// any time after this call has returned. If at all possible, callers should |
| 220 /// use [getUnusedPort] instead. |
| 221 Future<int> getUnsafeUnusedPort() async { |
| 222 var socket = await RawServerSocket.bind(InternetAddress.LOOPBACK_IP_V4, 0); |
| 223 var port = socket.port; |
| 224 await socket.close(); |
| 225 return port; |
| 226 } |
OLD | NEW |