reconnect method

Future<void> reconnect()

Force a reconnection attempt. This will cancel any pending reconnect timer and immediately attempt to reconnect.

This is useful when you detect that connectivity has been restored (e.g., using connectivity_plus in Flutter) and want to reconnect immediately instead of waiting for the next scheduled retry.

Example:

// In Flutter with connectivity_plus
connectivity.onConnectivityChanged.listen((result) {
  if (result != ConnectivityResult.none && transmit.isReconnecting) {
    transmit.reconnect();
  }
});

Implementation

Future<void> reconnect() async {
  if (_isClosed) {
    print('Transmit is closed, cannot reconnect');
    return;
  }

  if (_isManuallyDisconnected) {
    print('Transmit is manually disconnected, use connect() instead');
    return;
  }

  // Cancel any pending reconnect timer
  _reconnectTimer?.cancel();
  _reconnectTimer = null;
  _nextRetryTime = null;

  // Force cleanup of existing connection first
  await _cleanupConnection();

  // Reset reconnect attempts to allow fresh reconnection
  _reconnectAttempts = 0;
  _isReconnecting = false;

  // If we were connected, mark as disconnected first to trigger proper status update
  if (_status == TransmitStatus.connected) {
    _changeStatus(TransmitStatus.disconnected);
  }

  // Force immediate connection
  await _connect();
}