serg
serg

Reputation: 111265

How to make synchronous URL requests from actionscript?

I have a big loop in actionscript that sends lots of data to an url:

for(var i=0;i<1000;i++) {
    var request:URLRequest = new URLRequest();
    request.url = url;
    request.method = URLRequestMethod.POST;
    request.data = data;

    var loader:URLLoader = new URLLoader();

    loader.load(request);
}

The problem is because URLLoader can make only asynchronous calls, it sends all those thousands requests at once which kills webserver.

Also it acts a bit strange on top of that. Lets say the loop is running for 5 minutes. For whole 5 minutes there is no requests coming to web server, then at the end they all are sent at once. I already tried everything I could possibly think of (empty loops, callbacks, delays) - nothing helps. All requests are sent at once no matter what.

How to make requests synchronous, so it will send one request after another? Can anyone please suggest any solution?

Upvotes: 3

Views: 4973

Answers (1)

Patrick
Patrick

Reputation: 15717

You can't make synchronous call, but you can wait until the server answered back before sending another request.

But maybe there is a design flaw if really you have to send a thousand of request to a webserver in one loop ?

// small example to see how do the chaining call

class A extends EventDispatcher {
 private var urlLoader:URLLoader;
 private var urlRequest:URLRequest;
 private var sendCount:int=0;

 //......

 public function init(url:String):void{
  urlLoader=new URLLoader();
  urlLoader.addEventListener(Event.COMPLETE, sendData);
  urlRequest = new URLRequest();
  request.url = url;
  request.method = URLRequestMethod.POST;
  count=1000;
 }

 //....
 private var data:Object;

 //.....
 // 
 function sendData(e:Event=null):void{
  if (count-- > 0) {
   urlRequest.data = data; // put the data based on the counter
   urlLoader.load(urlRequest);
  } else {
   urlLoader.removeEventListener(Event.COMPLETE, sendData);
   dispatchEvent(new Event(Event.COMPLETE));
  }
 }
}


var a:A=new A();
a.addEventListener(Event.COMPLETE, function():void{
 trace("send finished");
}); // listen to the event complete so
    // you know when you send is finished

a.init("http://...."); // ok init your send
a.sendData(); // and start the send that will be chain each time the webserver answer

Upvotes: 6

Related Questions