Search code examples
streamdartserver-sideroutes

Dart Routing to Multiple Clients Concurrently


I'm having an issue with a Dart server. I'm trying to send multiple clients some information, but I don't have the information available for them right when they request it. That means I am using a Future and when that Future is complete, I will then send the data back to the client.

The problem, is that the server will not allow a second (or more) client to connect to the server while the first Future is still waiting to be completed.

Here's an example:

import "dart:async";
import "dart:io";
import "package:route/server.dart";

void main(List<String> args) {
  HttpServer.bind("localhost", 5000)
    .then((HttpServer server) {
      Router router = new Router(server)
      ..serve("/multi").listen(_multi);
    });
}

void _multi(HttpRequest request) {
  print("Waiting");
  new Timer(new Duration(seconds: 5), () {
    print("Replying");
    request.response.write("Hello There");
    request.response.close();
  });
}

Basically, if you only have one client connect at a time, this works perfectly fine. If, however, you have more than one client, the first client that connects will block the second client until the first client's connection has been closed.

I've also tried to use ..serve("/multi").asBroadcastStream()..., because I thought that would allow for multiple subscribers, but that had the same behavior.

Is there a way to do this?

Thanks.


Solution

  • I'm quite positive that it's not blocking any requests. I think it's your client (a browser?) that queues the connections to only use one socket (probably with keep-alive). This is very normal for browsers, to keep the number of sockets in use, to a minimum.

    The Dart server is designed to handle multiple requests at the same time, and the router package is not exception to that.