close method
Implementation
@override
Future<void> close() async {
// Cancel subscriptions first to prevent writes to closed sinks, then
// detach everything so a concurrent connect() never reuses a socket that
// is being torn down.
final cancellations = <Future<void>?>[
_inputSubscription?.cancel(),
_outputSubscription?.cancel(),
];
final socket = _socket;
final inputController = _inputController;
final outputController = _outputController;
_socket = null;
_channel = null;
_inputSubscription = null;
_outputSubscription = null;
_inputController = null;
_outputController = null;
for (final cancellation in cancellations) {
try {
await cancellation;
} catch (e) {
debugPrint('[WebSocketHandler] subscription.cancel failed: $e');
}
}
// sink.close() only completes once the socket was connected and its close
// handshake finished: it hangs forever after a failed connection attempt
// or while the handshake is still pending, so bound it.
try {
await socket?.sink.close().timeout(closeTimeout, onTimeout: () {});
} catch (e) {
debugPrint('[WebSocketHandler] socket.sink.close failed: $e');
}
// Close the controllers to prevent further messages and race conditions
try {
await inputController?.close();
} catch (e) {
debugPrint('[WebSocketHandler] inputController.close failed: $e');
}
try {
await outputController?.close();
} catch (e) {
debugPrint('[WebSocketHandler] outputController.close failed: $e');
}
}