I need to ping a website with ActionScript or Animate - actionscript-3

I had found this code ( I need to ping to an network with flash or actionscript )
Im not sure i understand it or how to use it exactly - I need for this to redirect to another frame if it worked and another if it failed
Is anyone able to help?
var ldr:URLLoader = new URLLoader();
ldr.addEventListener(HTTPStatusEvent.HTTP_STATUS, ldrStatus);
var url:String = "URL-TO-SITE";
var limit:int = 10;
var time_start:Number;
var time_stop:Number;
var times:int;
ping();
function ping():void
{
trace("pinging", url);
times = 0;
doThePing();
}
function doThePing():void
{
time_start = getTimer();
ldr.load(new URLRequest(url));
}
function ldrStatus(evt:*):void
{
if(evt.status == 200)
{
time_stop = getTimer();
trace("got response in", time_stop - time_start, "ms");
}
times++;
if(times < limit) doThePing();
}

Well it is trying to load a website 10 times and check the response. I would get rid of the limit though, it make no sense to try it 10 times in a row.
Don't forget that you will need a crossdomain.xml file on your server to be able to access it from flash.
You will need to add some more things for your purpose:
// add an event listener for a failed call
ldr.addEventListener(IOErrorEvent.IO_ERROR, ldrFailed);
ldr.addEventListener(SecurityErrorEvent.SECURITY_ERROR , ldrSecurityError);
function ldrFailed(evt:*):void
{
// loader failed (no internet connection), try to ping again
doFailedRedirect();
}
function ldrSecurityError(evt:*):void
{
// There is an internet connection but probably something is wrong with your crossdomain.xml
doFailedRedirect();
}
function doRedirect():void
{
// make your redirect here
}
function doFailedRedirect():void
{
// something went wrong, do your failed redirect here
}
Adjust the ldrStatus function:
function ldrStatus(evt:*):void
{
if(evt.status == 200)
{
// server responded with status 200 wich means everything is fine
time_stop = getTimer();
trace("got response in", time_stop - time_start, "ms");
doRedirect();
}
else
{
// there is an internet connection but the server returns something else (probably something is wrong with the server)
doFailedRedirect();
}
}

Related

How do I use this URLRequest script?

I started learning ActionScript 3 a week ago and have stumbled across a huge learning curve. I found this script on the internet:
var _loader:URLLoader;
var _request:URLRequest;
function loadData():void {
_loader = new URLLoader();
_request = new URLRequest("http://www.travoid.com/game/Purchase.php?gid=1");
_request.method = URLRequestMethod.POST;
_loader.addEventListener(Event.COMPLETE, onLoadData);
_loader.addEventListener(IOErrorEvent.IO_ERROR, onDataFailedToLoad);
_loader.addEventListener(IOErrorEvent.NETWORK_ERROR, onDataFailedToLoad);
_loader.addEventListener(IOErrorEvent.VERIFY_ERROR, onDataFailedToLoad);
_loader.addEventListener(IOErrorEvent.DISK_ERROR, onDataFailedToLoad);
_loader.load(_request);
}
function onLoadData(e:Event):void {
trace("onLoadData",e.target.data);
}
function onDataFailedToLoad(e:IOErrorEvent):void {
trace("onDataFailedToLoad:",e.text);
}
This all seems to work and is generating no errors or output, however my issue comes about when I use this next part of code (which I made)
function vpBuy(e:MouseEvent):void{
loadData();
if (e.target.data == "false") {
inf_a.visible = true;
inf_b.visible = true;
inf_c.visible = true;
inf_d.visible = true;
btn_ok.visible = true;
}
}
I get this error:
ReferenceError: Error #1069: Property data not found on
flash.display.SimpleButton and there is no default value. at
travoid_fla::MainTimeline/vpBuy() onLoadData
The part that is probably throwing this is:
if (e.target.data == "false") {
I was hoping e.target.data was what stored the value on the web page (which displays as false) but apparently not. With the code I found on the internet, what stores the information on the web page?
Thanks,
Ethan Webster.
The URLLoader load method is asynchronous, you have to wait the server response before triyng to get the result.
The functions onLoadData and onDataFailedToLoad are there to do that. When the response is well received the function onLoadData is called and you can get the data in e.target.data or _loader.data
The error in your function vpBuy is you try to access the data property on the object that triggered the MouseEvent (maybe a Button) and that object don't have such variable.
Try the following:
/** button clicked load the datas from the server **/
function vpBuy(e:MouseEvent):void
{
// load the datas from the server
loadData();
}
/** the datas are well loaded i can access them **/
function onLoadData(e:Event):void
{
trace("onLoadData",e.target.data);
if( e.target.data == "false" )
{
inf_a.visible = true;
inf_b.visible = true;
inf_c.visible = true;
inf_d.visible = true;
btn_ok.visible = true;
}
}
Hope this could help you :)

actionscript 3 - How do I use this URLRequest script?

I started learning ActionScript 3 a week ago and have stumbled across a huge learning curve. I found this script on the internet:
var _loader:URLLoader;
var _request:URLRequest;
function loadData():void {
_loader = new URLLoader();
_request = new URLRequest("http://www.travoid.com/game/Purchase.php?gid=1");
_request.method = URLRequestMethod.POST;
_loader.addEventListener(Event.COMPLETE, onLoadData);
_loader.addEventListener(IOErrorEvent.IO_ERROR, onDataFailedToLoad);
_loader.addEventListener(IOErrorEvent.NETWORK_ERROR, onDataFailedToLoad);
_loader.addEventListener(IOErrorEvent.VERIFY_ERROR, onDataFailedToLoad);
_loader.addEventListener(IOErrorEvent.DISK_ERROR, onDataFailedToLoad);
_loader.load(_request);
}
function onLoadData(e:Event):void {
trace("onLoadData",e.target.data);
}
function onDataFailedToLoad(e:IOErrorEvent):void {
trace("onDataFailedToLoad:",e.text);
}
This all seems to work and is generating no errors or output, however my issue comes about when I use this next part of code (which I made)
function vpBuy(e:MouseEvent):void{
loadData();
if (e.target.data == "false") {
inf_a.visible = true;
inf_b.visible = true;
inf_c.visible = true;
inf_d.visible = true;
btn_ok.visible = true;
}
}
I get this error:
ReferenceError: Error #1069: Property data not found on
flash.display.SimpleButton and there is no default value. at
travoid_fla::MainTimeline/vpBuy() onLoadData
The part that is probably throwing this is:
if (e.target.data == "false") {
I was hoping e.target.data was what stored the value on the web page (which displays as false) but apparently not. With the code I found on the internet, what stores the information on the web page?
Thanks, Ethan Webster.
that's trying to check data before it's loaded. because data loading is a time based process, not instant. so, you've to make your data check condition wait for data really load
i think you should use a callback function for vpBuy from "onLoadData"
or you can try moving your data check conditional into onLoadData function like
function onLoadData(e:Event):void {
trace("onLoadData",e.target.data);
if (e.target.data == "false")
{
inf_a.visible = true;
inf_b.visible = true;
inf_c.visible = true;
inf_d.visible = true;
btn_ok.visible = true;
}
}

Flash AS3 Call a WSDL in a for loop

I'm using the Flex SOAP web service, connecting to our WSDL and everything is dandy. However, I'm new to web services and the web guy is on holiday, so I'm a bit confused. The first thing I'm doing is running a check connection:
private function configXMLHandler(event:LoaderEvent):void {
fws.wsdl = checkWSDL;
fws.loadWSDL();
fws.addEventListener(LoadEvent.LOAD, wsdlLoaded);
}
private function wsdlLoaded(event:LoadEvent):void {
checkAbstract = fws.getOperation("retrieveAssetIdbyLabel");
checkAbstract.arguments = ["poll-asset-do-not-remove"];
var token:AsyncToken = checkAbstract.send();
token.addResponder(new Responder(checkAbstractResult, checkAbstractError));
}
private function checkAbstractError(event:FaultEvent):void {
trace('Error in the WSDL');
}
private function checkAbstractResult(event:ResultEvent):void {
if (event.result.returnCode == 0) {
trace('Web service check ok');
initContentLoader();
} else {
trace('Error in the WSDL');
)
}
}
This works fine, I get the result I expect, and so I move on. I then need to iterate through an XML list and call the same web service function for each asset in that XML, my thinking was to use a loop:
private function initContent(event:LoaderEvent):void {
assetList = event.target.content.asset;
for (var i:int = 0; i < assetList.length(); i++) {
assetAbstract = fws.getOperation("retrieveAssetIdbyLabel");
assetAbstract.arguments = [assetList[i + assetCount].assetLabel]; //get the current index in the xmllist + the assetCount, grab the corresponding assetLabel from the XML and pass that to the web service
trace(assetAbstract.arguments);
var assetToken:AsyncToken = assetAbstract.send();
assetToken.addResponder(new Responder(getAssetResult, getAssetError));
}
}
private function getAssetResult(event:ResultEvent):void {
var treasuresAsset:TreasuresAsset = new TreasuresAsset(event.result.returnCode, assetList[assetCount].asset.assetLabel, assetList[assetCount].asset.assetImage, assetList[assetCount].asset.assetDescription);
addChild(treasuresAsset);
assetCount++; //increase the asset count
}
private function getAssetError(event:FaultEvent):void {
trace(event.fault);
trace('An error occured when we tried to get an asset id in the loop');
}
I now get an error:
Error opening URL 'http://www.nhm.ac.uk/web-services/VisitorService/'
SOAPFault (Server): org.apache.axis2.databinding.ADBException: Unexpected subelement RetrieveAssetIdbyLabel
My immediate thought was that I need to create a new instance of the web service for each asset in the xml, and repeat my first code over and over. Can I use the web service only once, do you need to recreate the entire procedure?
Thanks.
OK, so I figured this out, and it was a simple XML namespace issue.
I replaced:
assetAbstract.arguments = [assetList[i + assetCount].assetLabel];
With:
var sender:String = assetList[i + assetCount].assetLabel;
assetAbstract.arguments = [sender];
And all is working.

Issue with geolocation timeout callback firing whether response received or not

I've implemented a timer for a HTML5 geolocation request as per this post Geolocation feedback while accepting the request
However I'm having an issue where the timer is called regardless of whether the navigator.geolocation.received response is true or not. Perhaps I'm missing something very obvious but I can't see what.
Basically, if I get the geo-location information I run the geo_success_action() function, but in every other case (geo-location failure, timeout on accepting location share, or non-existence of html5 geo-location support in the browser), I want to run the geo_failure_action() function.
However what's happening is that if geo-location is collected, my geo_success_action() function is called, and then when the timer runs out the geo_failure_action() is also called.
I had assumed that within var succeed, the setting of navigator.geolocation.received = true would be passed to my timedout function and therefore if navigator.geolocation.received was true, it wouldn't fire the resulting function.
Any thoughts?
var succeed = function(obj) {
navigator.geolocation.received = true;
if (!navigator.geolocation.timedout) {
geo_success_action( obj, json_url );
}
};
var failed = function(obj) {
navigator.geolocation.received = true;
if (!navigator.geolocation.timedout) {
geo_failure_action( json_url );
} else {
geo_failure_action( json_url );
}
};
var timedout = function() {
navigator.geolocation.timedout = true; // could be used for other callbacks to trace if its timed out or not
if (!navigator.geolocation.received){
geo_failure_action( json_url );
//alert('Timed Out');
} else {
null;
}
}
// Extend geolocation object
if ( navigator.geolocation ) {
navigator.geolocation.retrievePermission = function retrievePermission(succeed,failed,options,timeout) {
this.received = false; // reference for timeout callback
this.timedout = false; // reference for other callbacks
this.getCurrentPosition.apply(this,arguments); // actual request
// Trigger timeout with its function; default timeout offset 5000ms
if ( timeout ) {
setTimeout(timeout.callback,timeout.offset || 5000);
}
}
// New location request with timeout callback
navigator.geolocation.retrievePermission(succeed,failed,{},{
offset: 6000, // miliseconds
callback: timedout
});
// If geo-location not supported at all, do failure action
} else {
geo_failure_action( json_url );
}
I haven't tested, but this should work
var timedout = function() {
navigator.geolocation.timedout = true;
if( navigator.geolocation.received === undefined ) {
navigator.geolocation.received = true;
}
if (!navigator.geolocation.received){
geo_failure_action( json_url );
//alert('Timed Out');
} else {
null;
}
}

getting a shared object to expire after browser session in FLASH?

I'm looking for a way to play flash animated content once ( even as the user navigates to different HTML pages with similar flash content) and expire after a set amount of time or after the browser is closed.
I'm aware I could use a shared object for this but can't seem to find info about how to clear them at browser session end.
I am open to using javascript or PHP to assist .
your help is appreciated -
thanks -MW
Instead of using a SharedObject, you could create two simple server-side services: one that maintains the session, and one that exposes the session through a generated XML file that your flash application could use.
The first service would set some session variables and should be called whenever the video is played. It could look like this:
<?php
// start-video.php
session_start();
$_SESSION['hasWatchedVideo'] = true;
$_SESSION['watchedVideoAt'] = time();
?>
The second service is the one that generates the XML response based on the session. It might look like this:
<?php
// flash-config.php
session_start();
// set expiration to 5 min
define(VIDEO_TIMEOUT, 300);
$playVideo = "true";
if($_SESSION['hasWatchedVideo']
&& (time() - $_SESSION['watchedVideoAt']) < VIDEO_TIMEOUT) {
$playVideo = "false";
}
header("Content-Type: text/xml");
echo "<config><playVideo>{$playVideo}</playVideo></config>";
?>
Then from your Flash application, you could do this:
/**
* Called whenever the app is loaded.
*/
protected function init():void {
var u:URLLoader = new URLLoader();
u.addEventListener(Event.COMPLETE, onComplete);
u.load(new URLRequest("http://example.com/flash-config.php"));
}
/**
* Determines whether or not the video should play based on the
* config service response.
*/
protected function onComplete(e:Event):void {
var x:XML = new XML(e.target.data);
if(x.playVideo == 'true') {
playVideo();
}
}
/**
* Should be called either when the video starts playing. I just tied
* it to a user click here.
*/
protected function playVideo():void {
// call the service to update the session
var u:URLLoader = new URLLoader();
u.load(new URLRequest("http://example.com/start-video.php"));
// ... play video code ...
}
I think this approach gives you a bit more flexibility than using a SharedObject. Hope that helps.
UPDATE:
You could use a session cookie in the browser as well. Basically set the expiry date to '0' and the cookie will expire when the user closes the browser. (Note: when I tested this in Firefox, closing the tab was not enough to kill the cookie. The entire browser had to be closed.)
You can use ExternalInterface, or a utility library like this. Using the library, you could have code like this in your flash application:
function playVideo():void {
if(!CookieUtil.getCookie('playvideo')) {
CookieUtil.setCookie('playvideo', 'true', 0);
// ... play video code ...
}
}
Whenever the user closes the browser, the cookie will be cleared. Next time they visit your site, the video will play again. Not sure if this is more inline with what you're look for, but hope it helps.
I modified your code a tad so it will be killed on sesion end ...
the PHP ...
<?php
// flash_php_session_cookie.php
$cookie= "false";
if (isset($_COOKIE["cookie"]))
$cookie= "true";
else
setcookie("cookie", "true", 0);
echo "<config><cookie>{$cookie}</cookie></config>";
?>
the FLASH ...
// the folowing functions handle call coresponding PHP files to handle cookies ...
// re-configure these to the location of the swf ...
var flashConfigURL:String ="flash_php_session_cookie.php";
//Called whenever the app is loaded ...
function initCookieFunc():void {
var u:URLLoader = new URLLoader();
u.addEventListener(Event.COMPLETE, onComplete);
u.load(new URLRequest(flashConfigURL));
}
// Determines whether or not the cookie exists / (assumes theres a text field named T on the stage) ...
function onComplete(e:Event):void {
var x:XML = new XML(e.target.data);
if (x.cookie == 'false') {
T.appendText("cookie doesn't exist yet");
} else {
// cookie exists ...
T.appendText("cookie exists");
}
}
initCookieFunc();
I am going to keep a loose version of the "TIMEOUT"
version as well.
It's great to have an answer to this
Thanks again RJ for the invaluable code
-MW
You'll just have to expire the SharedObject yourself. It's not complicated.
This way your .swf will be completely self contained, not relying on anything external which IMO is a good thing.
package {
import flash.display.Sprite;
import flash.net.SharedObject;
import flash.net.SharedObjectFlushStatus;
public class SharedObjectExample extends Sprite {
private var _so:SharedObject;
private var _now:Date;
private var _last_played:Number;
private static const EXPIRE_TIME:Number = 1000 * 60 * 60 * 24; // 24hrs in msec
public function SharedObjectExample() {
// create a new date for the current time to compare against
_now = new Date;
// create a new shared object
_so = SharedObject.getLocal("application-name", "/");
// try read from the shared object
if (_so.data.last_played) _last_played = _now;
// if no value is set we play the video and set the current time
if (!_last_played) {
// play video here
_last_played = _now.time;
// check if the "cookie" has expired and it's time to play again
} else if ( _now.time - _last_played > EXPIRE_TIME) {
// play video here
_last_played = _now.time;
} else {
// do nothing
}
// and finally, save
saveValue();
}
private function saveValue(event:MouseEvent):void {
// i've removed the code that asks the user for permission if the request for storage is denied
_so.data.last_played = _last_played;
var flushStatus:String = null;
try {
flushStatus = _so.flush(1000);
} catch (error:Error) {
trace("Could not write SharedObject to disk");
}
}
}
}