Created
February 10, 2020 08:11
-
-
Save roughike/b7308f2f5a21bbd2ea7cb5321302f419 to your computer and use it in GitHub Desktop.
A simple dart webserver that distributes multiple connections across 6 Isolates.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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