serve method

Future<void> serve({
  1. dynamic address,
  2. int? port,
  3. ServerCredentials? security,
  4. ServerSettings? http2ServerSettings,
  5. int backlog = 0,
  6. bool v6Only = false,
  7. bool shared = false,
  8. bool requestClientCertificate = false,
  9. bool requireClientCertificate = false,
})

Starts the Server with the given options. address can be either a String or an InternetAddress, in the latter case it can be a Unix Domain Socket address.

If port is null then it defaults to 80 for non-secure and 443 for secure variants. Pass 0 for port to let OS select a port for the server.

Implementation

Future<void> serve({
  dynamic address,
  int? port,
  ServerCredentials? security,
  ServerSettings? http2ServerSettings,
  int backlog = 0,
  bool v6Only = false,
  bool shared = false,
  bool requestClientCertificate = false,
  bool requireClientCertificate = false,
}) async {
  // TODO(dart-lang/grpc-dart#9): Handle HTTP/1.1 upgrade to h2c, if allowed.
  Stream<Socket> server;
  final securityContext = security?.securityContext;
  if (securityContext != null) {
    final _server = await SecureServerSocket.bind(
      address ?? InternetAddress.anyIPv4,
      port ?? 443,
      securityContext,
      backlog: backlog,
      shared: shared,
      v6Only: v6Only,
      requestClientCertificate: requestClientCertificate,
      requireClientCertificate: requireClientCertificate,
    );
    _secureServer = _server;
    server = _server;
  } else {
    final _server = await ServerSocket.bind(
      address ?? InternetAddress.anyIPv4,
      port ?? 80,
      backlog: backlog,
      shared: shared,
      v6Only: v6Only,
    );
    _insecureServer = _server;
    server = _server;
  }
  server.listen((socket) {
    // Don't wait for io buffers to fill up before sending requests.
    if (socket.address.type != InternetAddressType.unix) {
      socket.setOption(SocketOption.tcpNoDelay, true);
    }

    X509Certificate? clientCertificate;

    if (socket is SecureSocket) {
      clientCertificate = socket.peerCertificate;
    }

    final connection = ServerTransportConnection.viaSocket(
      socket,
      settings: http2ServerSettings,
    );

    serveConnection(
      connection: connection,
      clientCertificate: clientCertificate,
      remoteAddress: socket.remoteAddressOrNull,
    );
  }, onError: (error, stackTrace) {
    if (error is Error) {
      Zone.current.handleUncaughtError(error, stackTrace);
    }
  });
}