Connecting Flash Applications to Remote Services Flash Remoting The Definitive Guide Tom Muck
Flash Remoting The Definitive Guide
Other resources from O’Reilly Related titles oreilly.com Programming ColdFusion MX ActionScript for Flash MX Pocket Reference ActionScript for Flash MX: The Definitive Guide ActionScript Cookbook oreilly.com is more than a complete catalog of O’Reilly books. You’ll also find links to news, events, articles, weblogs, sample chapters, and code examples. oreillynet.
Flash Remoting The Definitive Guide Tom Muck Beijing • Cambridge • Farnham • Köln • Paris • Sebastopol • Taipei • Tokyo
Chapter 1 CHAPTER 1 Introduction to Flash Remoting When I was an 11-year-old kid, I thought I was pretty good on a bike. I could do wheelies around the neighborhood, drive on dirt hills, jump ramps. It wasn’t enough, though. I wanted to make the transition to a minibike, which is basically a little bike with a lawn mower engine on it. If all I needed was my riding skills, I probably would have been set.
Flash Remoting technology is at the center of Macromedia’s Studio MX product suite, linking the server platforms with the client-side tools. Flash Remoting is built into Macromedia’s two application servers—ColdFusion MX and JRun 4. In addition, programmers using other technologies, such as ASP.NET or J2EE application servers, can purchase the Flash Remoting MX package so that Flash Remoting can be utilized on those servers.
• Java Management Extensions (JMX MBeans) • ColdFusion templates • ColdFusion Components • Server-Side ActionScript (SSAS) • ASP.NET pages • ASP.NET DLLs • SOAP-based web services • PHP pages In other words, a remote service might be a ColdFusion page, a PHP page, or an ASP.NET DLL, among other things. Flash Remoting allows Flash to make remote procedure calls on existing server-side services; server-side developers do not have to implement any Flash-specific APIs or adjust their design patterns.
Flash Player Client Server Flash Remoting Application server Figure 1-1. The Flash Player/Flash Remoting architecture ActionScript for Flash MX: The Definitive Guide (O’Reilly), if you need to push data from the server to Flash, such as in a chat application. Another option is to use Macromedia’s Flash Communication Server MX (FlashCom) for these types of applications. HTTP is a stateless protocol, so each request from the Flash Player opens a new connection to the server.
Action Message Format Flash 5 movies could send XML or name/value pairs across HTTP. Although these packets could be parsed automatically by Flash or manually by the developer using custom ActionScript, parsing could be slow because all XML data is sent as text strings encased by cumbersome tags. Flash Remoting is able to handle complex datatypes, such as objects, structures, arrays, and recordsets.
Flash Remoting requires browser support for binary POST. Because Netscape 6.x does not support binary POST, Flash Remoting does not work when the Flash Player is running within Netscape 6.x. The Flash Remoting call has no effect and no error is returned. This bug is fixed in Netscape 7. There are also issues with early versions of Safari and Chimera on the Macintosh.
..... /1/onResult...null..... Hello World from ColdFusion Component We can gain some insight into AMF by examining the request and response: • The content type of AMF is application/x-amf. • The AMF data is contained within the body of the request and response; it is primarily binary and is therefore difficult to show in print. • There are human-readable strings within the AMF data. The last point tells us that AMF is not entirely compressed.
to communicate with the Flash Player. Flash Player 7 supports SOAP directly, but it will be late 2004 until Flash Player 7 is widely distributed. The body of the AMF packet contains either an onResult event (i.e., response event) or an onStatus event (i.e., error event), which are both ActionScript objects. The Flash movie can then use the object directly, without any further parsing. Chapter 3 contains an in-depth discussion of the onStatus and onResult events.
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.
SELECT username FROM Users WHERE username = '#username#' and password = '#password#'
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.
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.
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.
Director MX, a separate multimedia authoring tool sold by Macromedia, can access Flash Remoting using the Flash MX Asset Xtra (which is basically an embedded version of Flash Player 6). For simplicity, this book assumes you are running Flash in a browser or a standalone Projector. Macromedia Flash Remoting Components Flash MX does not come with the Flash Remoting components preinstalled.
The Flash Remoting gateway is also sold separately for other application servers, including J2EE servers and Microsoft .NET, and must be installed and configured before it can be used. The trial version of the Flash Remoting gateway for J2EE and ASP.NET can also be downloaded from the Macromedia web site cited earlier. There are several open source implementations of the Flash Remoting gateway, apart from the versions supported by Macromedia.
See also Programming ColdFusion MX, by Rob Brooks-Bilson (O’Reilly), for information on ColdFusion. The trial/developer version of ColdFusion MX can be obtained together with Flash MX in the Macromedia Studio MX bundle. J2EE Application Servers and Java Servlet Engines The Flash Remoting gateway is available as a standalone product for any J2EEcompatible application server. It also works with a Java servlet engine that has been certified compatible with Sun’s servlet 2.2 or 2.
Microsoft ASP.NET Servers Flash Remoting is available as a standalone product for Microsoft ASP.NET servers. It allows remote services to be deployed as: • ASP.NET pages (.aspx pages) • DLL libraries (in the local assembly cache) • .NET executables • SOAP-based web services Flash Remoting does not work with “classic” ASP pages. You must have the ASP.NET framework running on your server. To run the ASP.NET framework you need IIS 5.
Figure 1-4. Flash timeline with attached client-side ActionScript Example 1-1. Client-side ActionScript code (HelloWorld.fla) /*** Section 1 ***/ #include "NetServices.as" /*** Section 2 ***/ // Assign myURL so it points to your Flash Remoting installation. var myURL = "http://localhost/flashservices/gateway"; var myServicePath = "com.oreilly.frdg.HelloWorld"; /*** Section 3 ***/ myResult = new Object( ); myResult.onResult = function (data) { trace("Data received from Server : " + data); }; myResult.
Example 1-1. Client-side ActionScript code (HelloWorld.fla) (continued) var myService = myServer.getService(myServicePath, myResult); myService.sayHello( ); Section 1 of Example 1-1 includes the NetServices.as library, which contains the code necessary to connect to a Flash Remoting–enabled server from Flash. If you do not include NetServices.as, the example will not work, but you will not receive any errors within the authoring environment. Section 2 initializes two variables: myURL and myServicePath.
service, and the onStatus( ) callback function is called if an error occurs. An object used to receive results from a remote service is called a responder object (or sometimes called a response object). Another way to trap events is to specify callback functions named the same as the service name with _Result and _Status appended to it. This technique, along with more information about callback functions and responder objects, is covered in Chapters 3 and 4. The System.
Server-Side Code In the next section, you’ll create the remote service required by this simple Flash movie. Once you have created the remote service, you can test the Flash movie using Control ➝ Test Movie. You should get the following output displayed in the Output window: Data received from Server : Hello World from servertype If you do not get this result: • Set the Output window to verbose mode (Window Debug Level ➝ Verbose).
After entering your ColdFusion administrative password, you should see a description of the component, similar to Figure 1-5. Figure 1-5. ColdFusion MX component description autogenerated by ColdFusion MX If you do not see the description, or if you get an error, check and fix any syntax errors and try again. Once you have verified that the ColdFusion component works via the browser, switch back to Flash and test the HelloWorld.fla movie created in Example 1-1.
SSAS can be consumed by Flash via Flash Remoting only and cannot be used to create other types of output such as HTML. The SSAS mechanism of ColdFusion MX and JRun 4 is actually a server-side implementation of the Rhino JavaScript parser, with some server-specific objects and methods added that allow the developer access to the functionality of and tags of ColdFusion (found in the ActionScript CF object). Methods of the CF object can be accessed as CF.methodName( ).
Java using JRun 4 or other J2EE servers For the Java example, we will implement our remote service as a simple Java class. Using Java as a remote service requires that the Flash Remoting gateway be installed on a Java application server such as Macromedia’s JRun 4 or IBM’s WebSphere. The Java version will not work with ColdFusion MX or Microsoft .NET servers. Create a new plain text file in any text editor, name it HelloWorld.java, and enter the code shown in Example 1-4. Example 1-4.
Figure 1-6. Visual Studio .NET project setup screen with settings for HelloWorld DLL Example 1-5. C# code for HelloWorld.cs using System; namespace com.oreilly.frdg { public class HelloWorld { public String sayHello ( ) { return "Hello World from ASP.NET DLL"; } } } Enter the code shown in Example 1-5 and compile the DLL using VS.NET’s Build ➝ Build Solution option, which creates HelloWorld.dll in the following directory: projectpath/bin/Debug Copy HelloWorld.
Switch back to the Flash movie and change the myURL variable in Example 1-1 to point to the .NET version of the Flash Remoting gateway, such as: var myURL = "http://yourservername/flashremoting/gateway.aspx"; This is the only change that has to be made to the Flash movie. It is necessary because the .NET version of the Flash Remoting gateway is implemented differently than the Java and ColdFusion MX versions. Save the Flash movie and test it. You should see the output from the DLL (“Hello World from ASP.
Example 1-7. PHP code for HelloWorld.php
Browse to the component with a web browser, and add the ?wsdl query string to the URL that points to the component: http://localhost/com/oreilly/frdg/HelloWorld.cfc?wsdl The browser should display the WSDL XML for the web service, as follows: PAGE 33If you see only a blank screen, view the page’s source in your browser (using View ➝ Source in Internet Explorer, for example). If you receive an error, correct any errors identified by the error message and try again. Like any URL, the web service URL may be cached depending on the browser settings, so you should reload/refresh the page to make sure the browser isn’t using the cached version. This web service can also be seen at the author’s site at: http://www.flash-remoting.com/oreilly/com/helloworld.
server-side implementation. He need only know the API for the remote services he intends to call. If he is using web services, he can query the .wsdl file on the server to discover the methods. This allows both the server-side code and the Flash application to be developed simultaneously, reducing production time and making testing and debugging easier. Even if one developer writes both the Flash and server-side code, the multitiered architecture is still advantageous.
7. The Flash Player receives the AMF data from the server and deserializes it into a native ActionScript datatype (in this case a String object). Depending on the data sent back, the deserialization is done within the Flash Player or the NetServices code. 8. Finally, the string is returned to an ActionScript callback function specified by the developer to receive data loaded from the server.
Presentation Tier The presentation tier is responsible for the application’s user interface (UI) and any client-side logic that is needed, such as client-side data validation. It communicates with the middle tier by sending and loading data on a request-driven basis. In most cases, the presentation layer consists of a Flash file embedded within an HTML page, but it can also be a Flash Standalone Projector running on the desktop, or even a Flash sprite within a Director Projector.
Presentation tier Flash Player XML/loadVariables Client Server Flash abstraction layer Middle tier Core business logic Data tier Database XML Other data source Figure 1-8. Flash 5 n-tiered application architecture with multilayered middle tier Presentation tier Flash Player AMF Client Server Flash Remoting adapter Core business logic Middle tier Data tier Database XML Other data source Figure 1-9.
entirely on the client side, as the UI can be created dynamically at runtime on the client’s machine. Furthermore, once the UI has been created or downloaded, only the updated data has to be sent back and forth to the server. This differs from dynamically generated HTML, which requires that the entire page be recreated on the server and served to the client each time the data or state of the application changes.
since Flash runs on the client side, which can be a much more variable and unknown environment than the server. For example, you can filter large sets of data in the middle tier where you have a known environment and resources, versus doing it on the client side within Flash where, depending on the client’s machine, it might not perform well. In this case, you may want to initially sort the data set on the server and then have any userinitiated sorts occur within the Flash Player.
Wrapping Up This chapter was only a brief introduction to the technology. You learned about the basic concepts of Flash Remoting, the benefits of Flash Remoting, and the advantages over traditional methods used in Flash 5. In addition, you saw a typical implementation of a Flash Remoting application and how it works in each server-side language. Chapter 2 digs deeper into Flash Remoting. It covers installation of the server-side gateway (where necessary) and the authoring components.