Skip to content

Instantly share code, notes, and snippets.

@roughike
Created February 10, 2020 08:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roughike/b7308f2f5a21bbd2ea7cb5321302f419 to your computer and use it in GitHub Desktop.
Save roughike/b7308f2f5a21bbd2ea7cb5321302f419 to your computer and use it in GitHub Desktop.
A simple dart webserver that distributes multiple connections 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();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment