DEV Community

kyorohiro (kiyohiro kawamura)
kyorohiro (kiyohiro kawamura)

Posted on

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.

Oldest comments (1)

Collapse
 
kyorohiro profile image
kyorohiro (kiyohiro kawamura)

if you can use mysql client at your http server code,

check here

pub.dev/packages/mysql1