Benefits

One of the key benefits of using Flash Remoting over XML or traditional HTML applications is that the application server no longer needs to handle any of the parsing or presentation of information. This frees resources on the server so that it can be better equipped to deal with more complex application logic and/or more users. In addition, session management can be handled on the client inside of the Flash movie rather than on the server. The server still keeps track of the session, but the developer doesn’t have to jump through hoops to keep track of users who don’t have cookies or track a user session across multiple pages. This equates to huge savings in development time and server resources.

Why Not XML?

I’ve talked about the benefits of Flash Remoting, but why not use XML? After all, using XML you could encapsulate all of the client/server communication within an ActionScript object and provide a simple API to transfer complex datatypes serialized with XML between Flash and the server. This would have the advantage of not requiring a server-side gateway and would work with Flash Player 5.

The main advantage of Flash Remoting over XML is that it relieves the developer from writing an entire layer of code on both the client and server. XML parsing is built into many of the popular server technologies, but it is cumbersome at best. However, Flash Remoting also has a number of additional advantages:

  • It automatically handles all datatype conversions between ActionScript and the server.

  • It can convert multiple complex datatypes.

  • It seamlessly supports multiple server-side technologies and application servers.

  • It allows remote services and web services to be called directly from Flash without requiring any additional server-side code to be written.

  • It provides a simple and consistent API for calling remote services and web services from the Flash Player.

  • It uses AMF to serialize data, which offers better performance than string-based serialization techniques (such as XML), even though AMF is not as widely supported as XML.

In a typical scenario involving an XML object being sent from a Flash 5 movie to a ColdFusion page, the Flash movie first has to create the XML string manually. Then it has to send the XML string to the ColdFusion page, which has to parse the XML before being able to utilize it. In addition, the server has to transform the result of any operation on the server back into XML to send the result to the Flash movie. The Flash movie then has to parse this XML once again to use the returned information. All of this parsing of data eats up valuable resources and bandwidth even before the application logic can be utilized.

In other words, a Flash 5 movie can’t use the data directly from the application server, and the application server can’t use the data directly from Flash 5.

Take a typical example of a username and password login. The ActionScript for the Flash movie could create a simple XML string and pass it to the ColdFusion page:

// Set up a new XML object.
var returnXML = new XML( );
returnXML.ignoreWhite = true;

// Set the callback function for the response from the server.
returnXML.onLoad = handleReply;

// Create an XML string.
// Form field variables are replaced in the string.
var my_xml = '<?xml version="1.0" encoding="iso-8859-1"?>';
my_xml += '<myValidation>';
my_xml += '<username>' + username + '</username>';
my_xml += '<password>' + password + '</password>';
my_xml += '</myValidation>';
var flash_xml_object = new XML(my_xml)

// Send it to the server and then load it into the my_xml object.
flash_xml_object.sendAndLoad("http://192.168.0.4/myLogin.cfm", returnXML);

function handleReply (result) {
  if (result) {
    if (this.firstChild.attributes.logged == "1") {
      greeting = "Hello " + this.firstChild.attributes.username;
      greeting += ". Login was successful";
    } else {
      greeting = "Login failed";
    }
  } else {
      greeting = "There was a communication failure.";
  }
}

A ColdFusion page to handle the logic would look like this:

<!---Deserialize the username and password from the XML--->
<cfset logged="1">
<cfset my_xml = XMLParse(URLDecode(GetHttpRequestData( ).content))>
<cfset username = my_xml.myValidation.username.xmltext>
<cfset password = my_xml.myValidation.password.xmltext>

<!---Query the database for matching entries--->
<cfquery name="myLogin" datasource="myDatasource">
  SELECT username FROM Users 
  WHERE username = '#username#' and password = '#password#'
</cfquery>

<!---Check whether a match was found--->
<cfif myLogin.RecordCount LT 1>
  <cfset logged = "0">
</cfif>

<!---Create an XML string to return to the Flash movie--->
<cfset returnXML = "<return username=""" & username>
<cfset returnXML = returnXML & """ logged=""" & logged & """ />">
<cfoutput>#returnXML#</cfoutput>

As you can see, the code is not intuitive—the XML is manually serialized into a string on both client and server, and the string has to be deserialized and turned into an XML object again on the Flash side. All of this code was created to send one simple XML object from the Flash movie to the server and back again. Imagine if this were something more complex, such as a recordset with 10 or 15 fields and 1,000 rows.

The Flash Remoting version of the previous code might look like this:

var myURL = "http://127.0.0.1/flashservices/gateway";
var myServer = NetServices.createGatewayConnection(myURL);
var myService = myServer.getService("com.oreilly.frdg.authentication", this);

myService.getLogin(username, password);

// The result handler for the getLogin( ) method invocation
function getLogin_Result (result_rs) {
  if (result_rs.getLength( ) < 1) {
    greeting = "Login failed";
  } else {
    greeting = "Hello " + result_rs.getItemAt(0).username;
    greeting += ". Login was successful";
  }
}

And the server-side code might look like this:

<cfcomponent displayName="login">
  <cffunction name="getLogin" returnType="query" access="remote">
    <cfargument name="username" type="string">
    <cfargument name="password" type="string">
    <cfquery name="myLogin" datasource="myDatasource">
      SELECT username FROM Users 
      WHERE username = '#username#' and password = '#password#'
    </cfquery>
    <cfreturn myLogin>
  </cffunction>
</cfcomponent>

The Flash Remoting code in this version is more intuitive; it defines a component containing a function that accepts two arguments directly from Flash. There is no manual parsing; the arguments to the function are passed as strings and a recordset is returned. If the recordset contained 15 fields and 1,000 rows, the server-side code would not look much different.

Using Flash Remoting is much simpler because the Flash movie does not have to package the request in any special format such as XML. Likewise, the ColdFusion Server does not have to package the result for the Flash movie. The data is simply passed back and forth as is and put to use. It is the difference between having a pizza delivered and making the dough and baking the pizza yourself. If the pizza is delivered, the only action you have to take on the pizza is to eat it.

Manually serializing and deserializing data has the advantage of working with Flash Player 5. However, when you consider the amount of client- and server-side code that you have to write, debug, and maintain just to provide basic support for serializing one datatype, the advantages of Flash Remoting become clearer. Considering all the datatypes that Flash Remoting supports and the fact that you can call remote services by name without writing any extra server-side code, Flash Remoting becomes quite attractive.

HTML and Server-Side Code

A typical HTML/server-side template application has problems similar to those in our XML example. The server-side code does not simply perform logic and return information; in many cases, it formats the data as well. Take this simple ColdFusion snippet as an example:

<!---Query the database for matching entries--->
<cfquery name="rsGetSearchResults" datasource="bookstore">
SELECT Title, Category, Pub_No FROM Books 
WHERE Title LIKE '%#form.searchfield#%'
</cfquery>
<!---Create an HTML table to display the matches--->
<table border="1">
  <tr> 
    <td>Title</td>
    <td>Category</td>
    <td>Pub_No</td>
  </tr>
  <cfoutput query="rsGetSearchResults" 
   startRow="#StartRow_rsGetSearchResults#" 
   maxRows="#MaxRows_rsGetSearchResults#"> 
    <tr> 
      <td>#rsGetSearchResults.Title#</td>
      <td>#rsGetSearchResults.Category#</td>
      <td>#rsGetSearchResults.Pub_No#</td>
    </tr>
  </cfoutput> 
</table>

This example queries a database and outputs the results as a table in the browser. This type of mixture of HTML and server-side code is commonplace in web application development. Notice, however, that the presentation of the content is created entirely by the application server. The HTML table doesn’t exist until the query is executed and the results are sent to the browser.

Using Flash Remoting, the application server code is utilized for the logic only—querying the database. The results of the query are returned to the Flash movie without any further parsing or manipulating. Using Flash Remoting, a ColdFusion component could be written as follows:

<cfcomponent displayName="searchBooks">
  <cffunction name="getTitles" returnType="query" access="remote">
    <cfargument name="search" type="string" default="%" />
    <cfquery name="rsGetSearchResults" datasource="bookstore">
     SELECT Title, Category, Pub_No FROM Books 
     WHERE Title LIKE '%#form.searchfield#%'
    </cfquery>
    <cfreturn rsGetSearchResults />
  </cffunction>
</cfcomponent>

Notice the line in bold, <cfreturn rsGetSearchResults />, which returns the entire recordset to the Flash movie as an ActionScript RecordSet object. The Flash movie, in turn, can use the recordset without any further parsing. For example, to attach the recordset to a DataGrid component in Flash, you can simply use this result handler in ActionScript:

function rsGetSearchResults_Result (result_rs) {
  myGridComponent.setDataProvider(result_rs);
}

Again, the Flash movie is working with the recordset as it comes from the server. No further parsing is necessary. Also, the ActionScript programmer has at his disposal a series of highly complex and interactive interface elements, unlike HTML forms, which are limited in functionality.

Another advantage is that the Flash movie looks the same in all browsers. The HTML language is ubiquitous, but the implementation is not uniform. Typically, you have to rely on CSS implementation, JavaScript being enabled, and/or cookies being enabled, or you have to create even more client-side code to handle the many possible user configurations.

Session Management in Flash

HTTP is a stateless protocol. The web server treats each page request coming from a browser as coming from an entirely new user. To create the illusion of maintaining state, many application servers have state management (or session management) in place to create a seamless experience for the end user. Session management is a bit of an art form for the application developer, as there are no sure-fire, out-of-the-box methods to maintain state in most application servers.

Typically, in a web application, you use cookies in conjunction with session variables to maintain state. This method won’t work if cookies are turned off on the client’s browser; therefore, you must store the information in a database or text file for 100% reliability. Furthermore, session management and variables eat up server memory. In an ASP application, for example, each typical user session consumes at least 4.5 KB, unless sessions are explicitly turned off. Also, unless a server application is cluster-aware, managing session state across a cluster can become complicated (because different servers in the cluster might handle successive requests).

Flash Remoting handles session state through means that are invisible to both the user and the server. Session information is sent with each and every AMF packet between the client and the server. No manual session management is required. In a rich client implementation, the Flash movie is loaded into the user’s browser only once, so session state is maintained automatically with every call to the server. In addition, because the session state is maintained within the Flash movie in the user’s browser, it makes little difference if the application server is clustered.

Get Flash Remoting: The Definitive Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.