The Flex sockets are so cool, you can connect to any type of TCP/IP server, because of security policy we cant add and change HTTP headers, but using SOCKET you can send any type of HTTP requests and working with responses. So if you hope the task was to implement a download manager with resume download support, SOCKET is a good solution for you.

The same with above, if you want to use printer with air, you can not find any poperties to accessing serial port or usb, but it is possible with a binary socket and serial proxy.

adobe-air

Following is a set of source code which is demonstrace how to use SOCKET to implement resume download and how to write received data.

  1. _socket.addEventListener( Event.CLOSE, socketClose ); // === COMPLETE
  2. _socket.addEventListener( Event.CONNECT, socketConnect );
  3. _socket.addEventListener( IOErrorEvent.IO_ERROR, uStreamIOErrorHandler );
  4. _socket.addEventListener( SecurityErrorEvent.SECURITY_ERROR, uStreamSecurityErrorHandler );
  5. _socket.addEventListener( ProgressEvent.SOCKET_DATA, socketData ); // === PROGRESS
  6. public function downloadFile ( $fileURL:String, $fileName:String, $pathToSave:String ) : void
  7. {
  8.     _isBusy            = true;
  9.     // _pathToTarget is path to file on server
  10.     // i.e. /getFile?myfile.jpg
  11.     // NOTE it cant be an url or anything, depends on serve config
  12.     _pathToTarget    = "/getFile?" + $fileURL.split( "/getFile?")[1];
  13.     _host            = URLUtil.getServerName( $fileURL );
  14.     var fl : File = new File().resolvePath( $pathToSave + File.separator + $fileName );
  15.     // PATH TO YOU DOWNLOAD FILE
  16.     var fl : File = new File().resolvePath( $pathToSave + File.separator + $fileName );
  17.     if ( fl.exists )
  18.     {
  19.         // position from download will be started
  20.         _downloadFromBytes    = fl.size;
  21.         // indicates is headers from socket data wah removed or not
  22.         _headerRemoved        = false;
  23.         // creating file stream to append downloaded data
  24.         _fileStream = new FileStream();
  25.         _fileStream.open( fl, FileMode.APPEND );
  26.         // check is socket is connected already
  27.         if ( _socket.connected )
  28.         {
  29.             sendRequest();
  30.         }
  31.         else
  32.         {
  33.             // connecting to your host and port
  34.             // i.e. host http://www.mydomain.com
  35.             // i.e. post 80
  36.             _socket.connect( _host, _port );
  37.         }
  38.     }
  39.     else
  40.     {
  41.         // if file is not exist downloading file with bacis download method.
  42.         _fileStream = new FileStream();
  43.         _urlRequest = new URLRequest( $fileURL );
  44.         _fileStream.open( fl, FileMode.WRITE );
  45.         _urlStream.load( _urlRequest );
  46.     }
  47. }
  48. private function socketConnect ( event:Event ) : void
  49. {
  50.     sendRequest();
  51. }
  52.  private function socketClose ( event:Event ) : void
  53. {
  54.     _fileStream.close();
  55. }
  56.  private function uStreamIOErrorHandler ( event:IOErrorEvent ) : void
  57. {
  58.     _fileStream.close();
  59. }
  60.  private function uStreamSecurityErrorHandler ( event:SecurityErrorEvent ) : void
  61. {
  62.     _fileStream.close();
  63. }
  64.  private function sendRequest () : void
  65. {
  66.     var request : String = "";
  67.     // _pathToTarget is path to file on server
  68.     // i.e. /getFile?myfile.jpg
  69.     // NOTE it cant be an url or anything, depends on serve config
  70.     request += "GET " + _pathToTarget + " HTTP/1.1" + "\n"
  71.     // host where file is hosted
  72.     // i.e. http://www.mydomain.com
  73.     request += "Host: " + _host + "\n";
  74.     // bytes from download will be started
  75.     request += "Range: bytes=" + _downloadFromBytes + "- ";
  76.     request += "\n\n";
  77.     // sending this request
  78.     sendMultiByte( request );
  79. }
  80. private function socketData ( event:ProgressEvent ) : void
  81. {
  82.     // creating holder for loaded bytes
  83.     var _loadedBytes        : ByteArray = new ByteArray();
  84.     // length of content to download from server
  85.     var _contentLength        : Number = 0;
  86.     // creating holder for bytes to APPEND to existed file on you HDD
  87.     var _bytesToWrite        : ByteArray = new ByteArray();
  88.     // if we have some data from socket
  89.     if ( _socket.bytesAvailable )
  90.     {
  91.         // reading bytes
  92.         _socket.readBytes( _loadedBytes, _prevBytesPosition );
  93.         // checking if headers was removed
  94.         // if not we must remove HTTP headers from socket data,
  95.         // to avoid writing this HTTP headers in to file body on HDD
  96.         if ( !_headerRemoved )
  97.         {
  98.             var loadedChars : String = "";
  99.             // making loop to remove all HTTP headers
  100.             for ( var i : int = 0; i < _loadedBytes.length; i++  )
  101.             {
  102.                 if ( loadedChars.indexOf( "13101310" ) > -1 || loadedChars.indexOf( "1313" ) > -1 )
  103.                 {
  104.                     _bytesToWrite.writeByte( _loadedBytes[ i ] );
  105.                 }
  106.                 else
  107.                 {
  108.                     loadedChars += String( _loadedBytes[i] );
  109.                 }
  110.             }
  111.             var str                : String = _loadedBytes.toString();
  112.             var httpStatus        : String;
  113.             var headerEndIndex    : int = str.indexOf( "Content-Transfer-Encoding: binary\r\n\r\n" );
  114.             // getting content length, it may be useful for progress calculation
  115.             var _range            : String = StringUtil.trim( str.substr( str.indexOf( "Content-Range: bytes " ) + 21, str.indexOf( "Connection:" ) - ( str.indexOf( "Content-Range: bytes " ) + 21 ) ) )
  116.             _contentLength = parseInt( _range.substr( _range.lastIndexOf( "/" ) + 1 ) );
  117.             // setting headerRemoved flag to true, to avoid next time checking for "clear" content
  118.             _headerRemoved = true;
  119.         }
  120.         else
  121.         {
  122.             _bytesToWrite = _loadedBytes;
  123.         }
  124.         // writing file data in to file on HDD
  125.         _fileStream.writeBytes( _bytesToWrite );
  126.     }
  127.     _prevBytesPosition = _socket.bytesAvailable;
  128.     event.bytesTotal = _contentLength;
  129.     dispatchEvent( event );
  130. }

And here is a simple sample of how to use binary socket and serial proxy:

  1. var serialPortApplication = function() {
  2.  
  3.     var socket;
  4.    
  5.     var onSocketData = function(event) {
  6.         var data = socket.readUTFBytes(socket.bytesAvailable);
  7.         air.trace(data);
  8.     };
  9.  
  10.     var createSocket = function() {
  11.    
  12.         socket = new air.Socket();
  13.             socket.addEventListener( air.ProgressEvent.SOCKET_DATA, onSocketData );
  14.  
  15.         // this is the port specified in the serial proxy config file
  16.             socket.connect( 'localhost', 5334 );
  17.    
  18.     };
  19.    
  20.     return {
  21.  
  22.         run   :   function() {
  23.           createSocket();
  24.         }
  25.    
  26.     };
  27.    
  28. }();
  29.  
  30. // Then....
  31.  
  32. serialPortApplication.run();

For help, advice, tips and tricks, challenges, feel free to visit ourDoNotYet forum or Submit your good resource to share.

Reminder: Unless stated otherwise, all resources published on this site are NOT for commercial use. To use any resource from this site for commercial purposes, please contact the author.

Related Posts