serveConnection method

Future<void> serveConnection({
  1. required ServerTransportConnection connection,
  2. X509Certificate? clientCertificate,
  3. InternetAddress? remoteAddress,
})

Implementation

Future<void> serveConnection({
  required ServerTransportConnection connection,
  X509Certificate? clientCertificate,
  InternetAddress? remoteAddress,
}) async {
  _connections.add(connection);
  handlers[connection] = [];
  // TODO(jakobr): Set active state handlers, close connection after idle
  // timeout.
  final onDataReceivedController = StreamController<void>();
  ServerKeepAlive(
    options: _keepAliveOptions,
    tooManyBadPings: () async =>
        await connection.terminate(ErrorCode.ENHANCE_YOUR_CALM),
    pingNotifier: connection.onPingReceived,
    dataNotifier: onDataReceivedController.stream,
  ).handle();
  connection.incomingStreams.listen((stream) {
    final handler = serveStream_(
      stream: stream,
      clientCertificate: clientCertificate,
      remoteAddress: remoteAddress,
      onDataReceived: onDataReceivedController.sink,
    );
    handler.onCanceled.then((_) => handlers[connection]?.remove(handler));
    handlers[connection]!.add(handler);
  }, onError: (error, stackTrace) {
    if (error is Error) {
      Zone.current.handleUncaughtError(error, stackTrace);
    }
  }, onDone: () async {
    // TODO(sigurdm): This is not correct behavior in the presence of
    // half-closed tcp streams.
    // Half-closed  streams seems to not be fully supported by package:http2.
    // https://github.com/dart-lang/http2/issues/42
    for (var handler in handlers[connection]!) {
      handler.cancel();
    }
    _connections.remove(connection);
    handlers.remove(connection);
    await onDataReceivedController.close();
  });
}