selectOneOf function

Future<ProtocolID> selectOneOf(
  1. List<ProtocolID> protos,
  2. P2PStream stream
)

SelectOneOf will perform handshakes with the protocols on the given list until it finds one which is supported by the muxer.

Implementation

Future<ProtocolID> selectOneOf(List<ProtocolID> protos, P2PStream<dynamic> stream) async {
  if (protos.isEmpty) {
    throw const NoProtocolsException();
  }

  try {
    // Try the first protocol with the initial handshake
    try {
      await selectProtoOrFail(protos[0], stream);
      return protos[0];
    } on ProtocolNotSupportedException {
      // First protocol not supported, try the others
    } catch (e) {
      // Other error, propagate it
      rethrow;
    }

    // Try the remaining protocols
    for (var i = 1; i < protos.length; i++) {
      try {
        await _trySelect(protos[i], stream);
        return protos[i];
      } on ProtocolNotSupportedException {
        // Protocol not supported, continue to the next one
        continue;
      }
    }

    // None of the protocols were supported
    throw ProtocolNotSupportedException(protos);
  } catch (e) {
    if (e is! ProtocolNotSupportedException) {
      await stream.reset();
    }
    rethrow;
  }
}