Dart: handle incoming HTTP requests in parallel

前端 未结 3 1205
情深已故
情深已故 2020-12-31 01:06

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

3条回答
  •  囚心锁ツ
    2020-12-31 01:46

    You need to:

    1. Set shared: true in HttpServer.bind
    2. Spawn some Isolates to handle the incoming requests in parallel.

    Here'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();
    }
    

提交回复
热议问题