Repository navigation
How to close HTTP connection properly? #2575
|
Reviving #729 How close TCP Connection? I tried with I'm Afraid that just cancel the Is there another way to close connection properly? (TCP) |
Replies: 2 comments
|
Two things that actually control this at the TCP level:
If you only need to stop consuming a stream mid-flight (not shut down the whole |
|
I tested this against a local server that streams a chunk every 50 ms and logs when the client's TCP connection goes away (dio 5.11.1, Dart 3.13.5, default
So your worry is right, but only for the subscription case. The cause is in Until that lands, use a CancelToken whenever you want to stop early. That path calls final token = CancelToken();
final res = await dio.get<ResponseBody>(
url,
options: Options(responseType: ResponseType.stream),
cancelToken: token,
);
final sub = res.data!.stream.listen(onChunk, onError: (_) {}); // cancel shows up as a DioException
// later, to stop and actually drop the TCP connection:
token.cancel();
await sub.cancel();
The reproduction script, |
cancelToken.cancel()aborts the request and stops theStreamfrom emitting more data, but it doesn't necessarily force-close the underlying TCP socket — Dart'sHttpClient(which dio's defaultIOHttpClientAdapterwraps) pools connections for reuse by default, so the socket can stay alive in the pool even after your request/subscription is done.Two things that actually control this at the TCP level:
dio.close(force: true)— this is the real "kill everything now" call.dio.close()withoutforcewaits for pending requests to finish before closing;force: trueimmediately aborts the underlyingHttpClientand all its open sockets, not just the one request.persistentConnection: falsein y…