startServing method

void startServing(
  1. void callbackHttp11(
    1. HttpRequest
    ),
  2. void callbackHttp2(
    1. ServerTransportStream
    ), {
  3. void onError(
    1. dynamic error,
    2. StackTrace
    )?,
})

Starts listening for HTTP/1.1 and HTTP/2 clients and calls the given callbacks for new clients.

It is expected that callbackHttp11 and callbackHttp2 will never throw an exception (i.e. these must take care of error handling themselves).

Implementation

void startServing(void Function(HttpRequest) callbackHttp11,
    void Function(http2.ServerTransportStream) callbackHttp2,
    {void Function(dynamic error, StackTrace)? onError}) {
  // 1. Start listening on the real [SecureServerSocket].
  _serverSocket.listen((SecureSocket socket) {
    var protocol = socket.selectedProtocol;
    if (protocol == null || protocol == 'http/1.1') {
      _http11Controller.addHttp11Socket(socket);
    } else if (protocol == 'h2' || protocol == 'h2-14') {
      var connection = http2.ServerTransportConnection.viaSocket(socket,
          settings: _settings);
      _http2Connections.add(connection);
      connection.incomingStreams.listen(_http2Controller.add,
          onError: onError,
          onDone: () => _http2Connections.remove(connection));
    } else {
      socket.destroy();
      throw Exception('Unexpected negotiated ALPN protocol: $protocol.');
    }
  }, onError: onError);

  // 2. Drain all incoming http/1.1 and http/2 connections and call the
  // respective handlers.
  _http11Server.listen(callbackHttp11);
  _http2Server.listen(callbackHttp2);
}