dart - 实现代理服务器

标签 dart httprequest httpresponse proxy-server dart-io

我正在尝试使用 Dart 实现代理服务器:在浏览器上运行的 Web 应用程序向本地运行的 dart 服务器应用程序(代理服务器)发出请求,然后代理服务器向外部服务器发出请求。然后,我将 CORS header 添加到将发送回客户端(网络应用程序)的响应中。

这是我实现代理服务器的方法:

import 'dart:io';
import 'dart:convert';

main() async {
  var server = await HttpServer.bind(InternetAddress.ANY_IP_V6, 8080);
  print('Server listening on port ${server.port}...');

  var client = 0;
  HttpClient proxy;
  await for (HttpRequest request in server) {
    print('Request received from client ${++client}.');

    // Adds CORS headers.
    request.response.headers.add('Access-Control-Allow-Origin', '*');

    proxy = new HttpClient()
      ..getUrl(Uri.parse('http://example.com/'))
          // Makes a request to the external server.
          .then((HttpClientRequest proxyRequest) => proxyRequest.close())

          // Sends the response to the web client.
          .then((HttpClientResponse proxyResponse) =>
              proxyResponse.transform(UTF8.decoder).listen((contents) =>
                request.response
                  ..write(contents)
                  ..close()
          ));

    print('Response sent to client $client.');
  }
}

大多数情况下这工作正常,但有时客户端只收到部分响应。我认为有时 request.response.close()request.response.write(contents) 完成执行之前执行,因此响应是在它完成之前发送的内容写完了。

有什么办法可以解决这个问题并且只在内容写入后才发送响应吗?谢谢。

最佳答案

收到第一个数据 block 后关闭响应 (..close())。您应该从那里删除 close() 并监听 proxyResponse 流的 close 事件并从那里关闭响应。

关于dart - 实现代理服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31358296/

相关文章:

javascript - Windows 中使用 XMLHttpRequest 的 React.JS POST 值

logging - RequestLogger 未拦截所有 http 请求

javascript - 使用 `GET` 的客户端请求表单,即使定义了 `POST`。 javascript iframe 是原因吗?

javascript - 如何正确编写http响应以便使用XHR进度事件监听器

xcode - 如何解决在Xcode上构建Archive时找不到的头文件?

ios - 无法验证下载服务器。您可能正在遭受中间人攻击

animation - 在 BottomSheet 中实现转换

image - Flutter pdf 生成对于图像太慢

c# - 中间件清零响应内容

api - 使用PowerApps进行Rest API调用