HttpClient.close() doesn’t close the connection

According to the HttpClient.close() documentation

Shut down the HTTP client. If force is false (the default) the HttpClient will be kept alive until all active connections are done. If force is true 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.

In fact, HttpClient.close() doesn’t close the client even with force true flag. And after close() call HTTP request can be sent from the client. Example

import "dart:io";
import "dart:async";
import "dart:convert";

var localhost = InternetAddress.LOOPBACK_IP_V4.address;

main() async {
  String helloWorld = "Hello world!";
  HttpServer server = await HttpServer.bind(localhost, 0);
  server.listen((HttpRequest request) {
    request.response.write(helloWorld);
    request.response.close();
    print("Request processing completed");
  });

  new Timer(new Duration(seconds: 1), () {
    print("Server closed");
    server.close();
  });

  HttpClient client = new HttpClient();

  client.getUrl(Uri.parse("http://${localhost}:${server.port}"))
      .then((HttpClientRequest request) {
    print("Request 1 sent");
    return request.close();
  }).then((HttpClientResponse response) {
    response.transform(UTF8.decoder).listen((content) {
      print("Response 1:" + content);
      client.close(force: true);
      print("HttpClient closed");

      client.getUrl(Uri.parse("http://${localhost}:${server.port}"))
          .then((HttpClientRequest request) {
        print("Request 2 sent");
        return request.close();
      }).then((HttpClientResponse response) {
        response.transform(UTF8.decoder).listen((content) {
          print("Response 2:" + content);
        });
      });
    });
  });
}

This program produces

Request 1 sent
Request processing completed
Response 1:Hello world!
HttpClient closed
Request 2 sent
Request processing completed
Response 2:Hello world!
Server closed

Tested on Dart VM version: 2.0.0-dev.8.0 (Fri Nov 17 14:04:05 2017) on “windows_x64”

Author: Fantashit

1 thought on “HttpClient.close() doesn’t close the connection

  1. Having the same issue and it is causing problem with the web server which has limited resource.

    Any update on this?

Comments are closed.