I am trying to write an HTTP server in Dart that can handle multiple requests in parallel. I have been unsuccessful at achieving the \"parallel\" part thus far.
Her
You need to:
shared: true
in HttpServer.bindHere's a barebones, minimal Dart server that distributes the incoming requests across 6 Isolates:
import 'dart:io';
import 'dart:isolate';
void main() async {
for (var i = 1; i < 6; i++) {
Isolate.spawn(_startServer, []);
}
// Bind one server in current Isolate
_startServer();
print('Serving at http://localhost:8080/');
await ProcessSignal.sigterm.watch().first;
}
void _startServer([List args]) async {
final server = await HttpServer.bind(
InternetAddress.loopbackIPv4,
8080,
shared: true, // This is the magic sauce
);
await for (final request in server) {
_handleRequest(request);
}
}
void _handleRequest(HttpRequest request) async {
// Fake delay
await Future.delayed(const Duration(seconds: 2));
request.response.write('Hello, world!');
await request.response.close();
}