pingStream function

Stream<PingResult> pingStream(
  1. Host host,
  2. PeerId peerId
)

Initiates a ping to the specified peer

Implementation

Stream<PingResult> pingStream(Host host, PeerId peerId) async* {
  _logger.warning('PingService.pingStream: Entered for peer ${peerId.toString()}');
  _logger.warning('PingService.pingStream: Calling host.newStream for peer ${peerId.toString()} with protocol ${PingConstants.protocolId}');
  final stream = await host.newStream(
    peerId,
    [PingConstants.protocolId],
    Context()
  );

  try {
    _logger.warning('PingService.pingStream: Returned from host.newStream for peer ${peerId.toString()}. Stream ID (if successful): ${stream.id}');
    stream.scope().setService(PingConstants.serviceName);

    final random = Random.secure();
    final seed = random.nextInt(1 << 32);
    final randomReader = Random(seed);

    while (true) {
      final result = await _ping(stream, randomReader);
      if (result.hasError) {
        yield result;
        break;
      }

      if (result.rtt != null) {
        host.peerStore.metrics.recordLatency(peerId, result.rtt!);
      }

      yield result;
    }
  } catch (e) {
    yield PingResult(error: e);
  } finally {
    stream.reset();
  }
}