connect method

Future<void> connect()

Connect to the remote session.

Implementation

Future<void> connect() async {
  if (_state == RemoteSessionState.connected) return;

  _setState(RemoteSessionState.connecting);

  try {
    final headers = <String, dynamic>{};
    if (_authToken != null) {
      switch (_authMethod) {
        case RemoteAuthMethod.token:
          headers['Authorization'] = 'Bearer $_authToken';
        case RemoteAuthMethod.apiKey:
          headers['X-Api-Key'] = _authToken;
        default:
          break;
      }
    }

    _socket = await WebSocket.connect(_url, headers: headers);
    _setState(RemoteSessionState.connected);
    _reconnectAttempts = 0;

    // Create session info.
    final uri = Uri.parse(_url);
    _sessionInfo = RemoteSessionInfo(
      sessionId: 'remote_${DateTime.now().millisecondsSinceEpoch}',
      hostId: uri.host,
      state: RemoteSessionState.connected,
      connectionType: RemoteConnectionType.direct,
      connectedAt: DateTime.now(),
      remoteAddress: uri.host,
      remotePort: uri.port,
    );

    _eventController.add(RemoteConnected(_sessionInfo!));

    // Start heartbeat.
    _startHeartbeat();

    // Listen for messages.
    _socket!.listen(
      (data) => _handleMessage(data as String),
      onDone: () => _handleDisconnect('Connection closed'),
      onError: (e) => _handleDisconnect('Connection error: $e'),
    );
  } catch (e) {
    _setState(RemoteSessionState.error);
    _eventController.add(RemoteError('Failed to connect', e));
    _scheduleReconnect();
  }
}