forwardPorts method

Future<Future<void> Function()> forwardPorts({
  1. required int fromHost,
  2. required int toDevice,
  3. String? device,
  4. String protocol = 'tcp',
})

Sets up port forwarding on the attached device. Returns a function that stops the port forwarding when called.

If there is more than 1 device attached, decide which one to use by passing device.

Throws if there are no devices attached.

See also:

Implementation

Future<Future<void> Function()> forwardPorts({
  required int fromHost,
  required int toDevice,
  String? device,
  String protocol = 'tcp',
}) async {
  await _adbInternals.ensureServerRunning();

  final result = await io.Process.run(
    'adb',
    [
      if (device != null) ...[
        '-s',
        device,
      ],
      'forward',
      '$protocol:$fromHost',
      '$protocol:$toDevice',
    ],
    runInShell: true,
  );

  if (result.stdErr.isNotEmpty) {
    _handleAdbExceptions(result.stdErr);

    throw Exception(result.stdErr);
  }

  return () async {
    final result = await io.Process.run(
      'adb',
      [
        if (device != null) ...[
          '-s',
          device,
        ],
        'forward',
        '--remove',
        '$protocol:$fromHost',
      ],
      runInShell: true,
    );

    if (result.stdErr.isNotEmpty) {
      _handleAdbExceptions(result.stdErr);

      throw Exception(result.stdErr);
    }
  };
}