startServer method

  1. @override
Future<int> startServer({
  1. int port = 0,
})
override

Starts a server on the given port (for server-based transports).

This method is called only when using the TransportMode.ephemeralServer mode. It should start an HTTP server that uses the handleRequest method to process incoming requests.

port is the port to bind to (0 for random port) Returns the bound port number.

Implementation

@override
Future<int> startServer({int port = 0}) async {
  // Bind to loopback so the test client cannot be accessed externally.
  _server = await HttpServer.bind(
    InternetAddress.loopbackIPv4,
    port,
    shared: true,
  );

  // Forward all requests to the callback.  Any asynchronous errors are
  // surfaced on stderr to aid debugging.
  _server!.listen((req) {
    try {
      final result = _onRequest(req);
      if (result is Future) {
        result.catchError((Object e, StackTrace st) {
          stderr.writeln('IoRequestHandler error: $e\n$st');
        });
      }
    } on Object catch (e, st) {
      stderr.writeln('IoRequestHandler error: $e\n$st');
      // Ensure the response is closed to avoid hanging sockets.
      _safeClose(req.response);
    }
  });

  return _server!.port;
}