Rafael
Rafael

Reputation: 358

Implementing a proxy server

I'm trying to implementing a proxy server with Dart: a web app running on the browser makes a request to my dart server app (proxy server) running locally, and then the proxy server makes a request to the external server. I then add CORS headers to the response that is going to be sent back to the client (web app).

Here's how I implemented the proxy server:

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

This works fine most of the times, but sometimes the client only receives part of the response. I think sometimes the request.response.close() is being executed before the request.response.write(contents) finished executing, and so the response is sent before it has finished writing the contents.

Is there any way to solve this and only send the response once the contents have been written? Thanks.

Upvotes: 5

Views: 1600

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657058

You close the response after you receive the first chunk of data (..close()) . You should remove the close() from there and listen to the close event of the proxyResponse stream and close the response from there.

Upvotes: 2

Related Questions