Home  >  

Adobe AIR in Action: Monitoring Sockets

Author photo
AddThis Social Bookmark Button
lott.jpg
The internet is a great place, but it has two drawbacks. You can’t access it everywhere, and sometimes sites and services go down. Modern web-enabled applications need to expect lapses in network connectivity. So it is not a surprise that the ability to gracefully handle sometimes-connectedness is one of the most heralded features of AIR.

I started exploring AIR’s network detection classes while co-writing Adobe AIR in Action, and was reminded that a lot of neat communication can happen over sockets. You can connect to many servers on ports other than the standard HTTP port to access a variety of services. For example, you can connect to a National Institutes of Standards and Times (NIST) server on port 13 to get the current time and date.

Writing an application that checks whether the NIST server is available, before connecting the socket to get the time, is easily accomplished in AIR. First, you need to import the SocketMonitor class, which resides in an archive file called servicemonitor.swc. Flex Builder includes this library automatically. Flex SDK users can find it in the frameworks/libs/air directory, while Flash users will see it in the AIK/frameworks/libs/air directory of the Flash CS3 installation directory.

Next you can get the monitor up and running in three easy steps:

  1. Create a SocketMonitor instance, passing the server and port to the constructor.
  2. Add a listener for status events on the monitor. In the corresponding handler function, access the monitor’s Boolean available property.
  3. Start the monitor.

The monitor’s available property is set based on the results of polling the connection. By default the monitor only polls when it is first started and when it is informed of network status changes. You can optionally set the monitor’s pollInterval to check the status more often.

After confirming that you can connect to the server, the only remaining task is to retrieve the time. This is just a matter of connecting the socket, listening to its data events, and parsing the data that comes across. The below example does just that. As long as it is online, it uses a timer to retrieve the updated time every ten seconds.

Here is the full application:

 
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="creationCompleteHandler();">

	<mx:Script>
		<![CDATA[
		import air.net.SocketMonitor;

		private var _monitor:SocketMonitor;
		private var _socket:Socket;
		private var _timer:Timer;
		private const SERVER:String = "time-A.timefreq.bldrdoc.gov";
		private const PORT:int = 13;
			
		private function creationCompleteHandler():void {
 		    _monitor = new SocketMonitor(SERVER, PORT);
 		    _monitor.addEventListener(StatusEvent.STATUS, statusHandler);
 		    _monitor.start();
 
 		    _socket = new Socket();
 		    _socket.addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
 
 		    _timer = new Timer(10000);
 		    _timer.addEventListener(TimerEvent.TIMER, timerHandler);
 		}
			
		private function statusHandler(event:StatusEvent):void {
 		    if(!_monitor.available) {
  		        timeText.text = "Server unavailable. Will reconnect when the server is next available.";
  		        _timer.stop();
  		    }
 		    else {
  		        timerHandler();
  		        _timer.start();
  		    }
 		}
			
		private function socketDataHandler(event:ProgressEvent):void {
 		    var fullTime:String = _socket.readUTFBytes(_socket.bytesAvailable);
 		    var time:String = fullTime.split(" ")[2];
 		    timeText.text = "The current time (UTC) is: " + time;
 		    _socket.close();
 		}
			
		private function timerHandler(event:TimerEvent = null):void {
 		    if(_monitor.available && !_socket.connected) {
  		        _socket.connect(SERVER, PORT); 
  		    }
 		}
		]]>
	</mx:Script>
	
	<mx:Text id="timeText" width="100%" height="100%" />

</mx:WindowedApplication>

While the program can’t retrieve the time if the NIST server is down, it can seamlessly handle any lapses in connectivity. Try disabling and enabling your internet connection while the application is running, and you will see that it responds accordingly. This basic example demonstrates the simplicity and usefulness of detecting network connections in an AIR application.

To learn more about detecting network connectivity and other AIR functionality, you can order your copy of our book at Manning Publications (shipping in late July). The ebook is available July 13.

Read more from Kathryn Rotondo. Kathryn Rotondo's Atom feed krotondo on Twitter

  • comments: 5

Comments

5 Comments

AJ said:

Author description linked to a wrong page.

Kathryn said:

Hi AJ, I noticed that too. The good folks at O'Reilly are fixing it; in the meantime you can find my bio at http://www.oreillynet.com/pub/au/3487.

Sean said:

Is there a way in AIR to set AIR Application's HTTP Proxy Server setting for something like Download Manager Use Case? Appreciate your response.

KIELSOFT said:

Please can you respond to Sean post, asking about HTTP proxy server setting for Air.

And can you please display how the above code can be used in Flash for Air.

EZEKIEL said:

CAN YOU PLS RESPOND TO SEAN POST ABOUT HTTP PROXY SERVER WITH AIR

Leave a comment


Tag Cloud

Question of the Week: Dream App

If you had an unlimited budget and unlimited resources what application would you build and why would you build it?

Answer

Latest Features

Recommended for You

@InsideRIA on Twitter

Archives

  • Or, visit our complete archive.  

About This Site

Welcome to the premiere community site for all things RIA sponsored by O'Reilly Media and Adobe Systems Incorporated.