Dart ConnectionTask
last modified October 18, 2026
The ConnectionTask class in Dart represents a cancelable socket
connection attempt. It is used with socket connections and provides control
over pending connection attempts.
ConnectionTask allows cancellation of pending connections. It's part of
Dart's dart:io library for network operations.
Basic Definition
ConnectionTask holds a Future that completes with the connected
socket, together with a cancel method. It is returned by
Socket.startConnect and RawSocket.startConnect; the
regular connect methods return a plain Future.
Its key feature is cancellation. Timeouts can be added by applying
Future.timeout to the task's socket future.
Basic ConnectionTask Usage
This example shows basic connection establishment using ConnectionTask.
import 'dart:io';
Future<void> main() async {
var server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
var task = await Socket.startConnect(server.address, server.port);
try {
var socket = await task.socket;
print('Connected to ${socket.remoteAddress.address}');
socket.destroy();
} finally {
await server.close();
}
}
We start a local server and use Socket.startConnect, which returns a Future that completes with a ConnectionTask. Awaiting task.socket yields the connected socket.
$ dart main.dart Connected to 127.0.0.1
Canceling a Connection
This example demonstrates canceling an ongoing connection attempt.
import 'dart:io';
Future<void> main() async {
var task = await Socket.startConnect('10.255.255.1', 80);
// Cancel after 2 seconds
Future.delayed(Duration(seconds: 2), () {
task.cancel();
print('Connection canceled');
});
try {
var socket = await task.socket;
print('Connected to ${socket.remoteAddress}');
socket.destroy();
} on SocketException catch (e) {
print('Connection failed: ${e.message}');
}
}
We start a connection to an unreachable address and cancel it after 2 seconds. The cancel() method aborts the attempt and makes task.socket complete with a SocketException.
$ dart main.dart
Connection canceled
Connection failed: Connection attempt cancelled, host: InternetAddress('10.255.255.1', IPv4), port: 80
Connection Timeout
This example shows implementing a connection timeout using ConnectionTask.
import 'dart:async';
import 'dart:io';
Future<void> main() async {
var task = await Socket.startConnect('10.255.255.1', 80);
try {
var socket = await task.socket.timeout(Duration(seconds: 3));
print('Connected to ${socket.remoteAddress}');
socket.destroy();
} on TimeoutException catch (e) {
task.cancel();
print('Connection failed: $e');
}
}
We attempt to connect to an unreachable address with a 3-second timeout. Future.timeout completes with an error if the connection takes too long, and we cancel the task when that happens.
$ dart main.dart Connection failed: TimeoutException after 0:00:03.000000: Future not completed
Multiple Connection Attempts
This example demonstrates managing multiple connection attempts.
import 'dart:async';
import 'dart:io';
Future<void> main() async {
var server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
var targets = [
('10.255.255.1', 80),
('10.255.255.2', 80),
(server.address.address, server.port),
];
try {
for (var (host, port) in targets) {
var task = await Socket.startConnect(host, port);
print('Connecting to $host...');
try {
var socket = await task.socket.timeout(Duration(seconds: 2));
print('Connected to $host');
socket.destroy();
return;
} on TimeoutException {
task.cancel();
print('Failed to connect to $host: timeout');
} on SocketException catch (e) {
print('Failed to connect to $host: ${e.message}');
}
}
print('All connection attempts failed');
} finally {
await server.close();
}
}
We try connecting to multiple targets sequentially. The first successful connection stops the attempts. Each attempt has a 2-second timeout and is canceled when it times out.
$ dart main.dart Connecting to 10.255.255.1... Failed to connect to 10.255.255.1: timeout Connecting to 10.255.255.2... Failed to connect to 10.255.255.2: timeout Connecting to 127.0.0.1... Connected to 127.0.0.1
Tracking Connection Completion
This example shows how to track when a connection attempt finishes.
import 'dart:io';
Future<void> main() async {
var server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
var task = await Socket.startConnect(server.address, server.port);
print('Connection attempt started');
try {
var socket = await task.socket;
print('Connected to ${socket.remoteAddress.address}');
socket.destroy();
} finally {
print('Connection attempt completed');
await server.close();
}
}
ConnectionTask exposes the socket Future rather than a stream of progress events. We print status before and after awaiting that Future.
$ dart main.dart Connection attempt started Connected to 127.0.0.1 Connection attempt completed
Best Practices
- Always handle errors: Connection attempts can fail for many reasons
- Use timeouts: Prevent indefinite waiting for connections
- Clean up resources: Close sockets when done
- Use startConnect: Use Socket.startConnect when the attempt must be cancelable
- Log outcomes: Record whether the attempt succeeded, failed, or was canceled
Source
Dart ConnectionTask Documentation
This tutorial covered Dart's ConnectionTask class with practical examples showing connection management, cancellation, timeouts, and completion tracking.
Author
List all Dart tutorials.