2

我的服务器端 Dart Web 应用程序为某些请求提供图像文件。

简化,这是它目前所做的:

   HttpServer.bind(InternetAddress.ANY_IP_V4, 80)
    .then((HttpServer server) {    
      server.listen((HttpRequest request) {      
        request.response.statusCode = HttpStatus.OK;
        request.response.headers.contentType = ContentType.parse("image/jpg");
        var file = new File("C:\\images\\myImage.jpg");
        file.readAsBytes().then((List<int> bytes) {
          bytes.forEach((int b) => request.response.writeCharCode(b)); // slow!
          request.response.close();       
        });    
      }
   }

这行得通,但它相当慢,我怀疑通过单独写入每个字节HttpResponse.writeCharCode是在这里减慢速度的原因。

不幸的是,没有像HttpResponse.writeAllCharCodes这样的东西。有writeAll,但它调用字节数组的每个元素——我们需要写入原始字节。toString()

有什么建议么?

4

2 回答 2

3

我认为这可能会对您有所帮助-我的速度提高了大约 4-5 倍:

我将在这里添加我的完整示例:

Future<ServerSocket> future = ServerSocket.bind("127.0.0.1", 1000);
future.then((ServerSocket sock) {
  HttpServer s = new HttpServer.listenOn(sock);

  s.listen((HttpRequest req) {
    req.response.statusCode = HttpStatus.OK;
    req.response.headers.contentType = ContentType.parse("image/png");
    var file = new File("someImage.png");

    // Average of about 5-7ms
    Future f = file.readAsBytes();
    req.response.addStream(f.asStream()).whenComplete(() {
      req.response.close();
    });
    // Average of ~25-30ms
    /*
    file.readAsBytes().then((List<int> bytes) {
      bytes.forEach((int b) => req.response.writeCharCode(b)); // slow!
      req.response.close();       
    });
    */ 
  });
});

这能解决您的问题吗?

问候罗伯特

于 2014-04-27T05:57:23.207 回答
1

考虑到@Anders Johnsen 的评论,您可以这样做。

File f = new File( "image_file.png" )
  ..readAsBytes()
    .asStream()
    .pipe( req.response );

我个人喜欢这个,因为它利用了 Darts 方法级联,但两者都有效。

于 2015-01-23T12:43:16.200 回答