openStream function

Future<P2PStream> openStream(
  1. BasicHost host,
  2. PeerId serverPeerId,
  3. String protocolId, {
  4. int maxRetries = 3,
})

Open a new protocol stream to the server with retry logic.

Implementation

Future<P2PStream> openStream(
  BasicHost host,
  PeerId serverPeerId,
  String protocolId, {
  int maxRetries = 3,
}) async {
  for (int attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      final stream = await host.newStream(serverPeerId, [protocolId], core_context.Context());
      return stream;
    } catch (e) {
      if (attempt == maxRetries) rethrow;
      stderr.writeln('    Stream open attempt $attempt/$maxRetries failed ($e), retrying...');
      await Future.delayed(const Duration(seconds: 1));
    }
  }
  throw StateError('unreachable');
}