close method

  1. @override
Future<void> close()
override

Implementation

@override
Future<void> close() async {
  // Cancel subscriptions first to prevent writes to closed sinks
  try {
    await _inputSubscription?.cancel();
  } catch (e) {
    debugPrint('[WebSocketHandler] inputSubscription.cancel failed: $e');
  }
  try {
    await _outputSubscription?.cancel();
  } catch (e) {
    debugPrint('[WebSocketHandler] outputSubscription.cancel failed: $e');
  }
  _inputSubscription = null;
  _outputSubscription = null;

  try {
    await _socket?.sink.close();
  } 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');
  }

  _inputController = null;
  _outputController = null;
  _channel = null;
  _socket = null;
}