Dart program will not exit if response body is unread
import 'dart:convert';
import 'dart:io';
final url = Uri.http('127.0.0.1', '');
Future<void> main() async {
final httpClient = HttpClient();
httpClient.findProxy = null;
final req = await httpClient.getUrl(url);
final res = await req.close();
// await res.transform(utf8.decoder).join();
httpClient.close();
print('end of main');
}
The program will not terminate if the line is commented out. Should we read the response body anyway if it is not important, or discard it somehow?
Solution 1:
You can use force: true
on your HttpClient
object if you are sure you just want to kill all ongoing connections:
Shuts down the HTTP client.
If
force
isfalse
(the default) the HttpClient will be kept alive until all active connections are done. Ifforce
istrue
any active connections will be closed to immediately release all resources. These closed connections will receive an error event to indicate that the client was shut down. In both cases trying to establish a new connection after calling close will throw an exception.
https://api.dart.dev/stable/2.15.1/dart-io/HttpClient/close.html
Alternative, you can use drain()
on your HttpClientResponse
if you just want to get the answer but throw it away immediately.