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) {
    _secureServer = await SecureServerSocket.bind(
        address ?? InternetAddress.anyIPv4, port ?? 443, securityContext,
        backlog: backlog,
        shared: shared,
        v6Only: v6Only,
        requestClientCertificate: requestClientCertificate,
        requireClientCertificate: requireClientCertificate);
    server = _secureServer;
  } else {
    _insecureServer = await ServerSocket.bind(
      address ?? InternetAddress.anyIPv4,
      port ?? 80,
      backlog: backlog,
      shared: shared,
      v6Only: v6Only,
    );
    server = _insecureServer;
  }
  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.remoteAddress,
    );
  }, onError: (error, stackTrace) {
    if (error is Error) {
      Zone.current.handleUncaughtError(error, stackTrace);
    }
  });
}