Isolate and Dart Http Server

kyorohiro

kyorohiro (kiyohiro kawamura)

Posted on April 4, 2021

Isolate and Dart Http Server

I have explained various things so far. how to start http server and to start https server and to get SSL and to run isolate.

In this time, I want to explain, how to run http server with isolate.

Hello Isolae Http Server

But, it is not so difficult, because Dart 's HttpServer class support isolate.

you can do it just by seting shared option is true,

import 'dart:io' as io;
import 'dart:isolate' as iso;

onIsolateMain(message) async {
  var server = await io.HttpServer.bind("0.0.0.0", 8080, shared: true);
  await for (var request in server) {
    print("${request.uri}");
    request.response.write("${message}");
    request.response.close();
  }
}

main() async {
  var server = await io.HttpServer.bind("0.0.0.0", 8080, shared: true);
  server.listen((request) {
    print("${request.uri}");
    request.response.write("parent");
    request.response.close();
  });
  //
  for (int i = 0; i < 10; i++) {
    iso.Isolate.spawn(onIsolateMain, "${i}");
  }
}
Enter fullscreen mode Exit fullscreen mode
$ curl http://tetorica.net:8080/
parent
$ curl http://tetorica.net:8080/
1
$ curl http://tetorica.net:8080/
0
$ curl http://tetorica.net:8080/
4
Enter fullscreen mode Exit fullscreen mode

Dart's HttpServer distribute access to server object.

💖 💪 🙅 🚩
kyorohiro
kyorohiro (kiyohiro kawamura)

Posted on April 4, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

About Dart's  Isolate (1)
dart About Dart's Isolate (1)

April 4, 2021