Flash Remoting

[ LiB ]  

Flash Remoting isn't so much a product as it is a feature supported in Flash. Remoting is a way that Flash apps can directly invoke methods residing on your application server. This means, anything your server can do, Flash can do. If your application server has a method (that is, a function) that searches a database and returns the results, Flash can trigger it and get the data back into your Flash app. You can think of Remoting as a channel over which Flash connects to methods residing on the application server.

To set up Remoting, follow these three steps:

  1. Install and enable Remoting on your server. (It's built in to ColdFusion MX.)

  2. Install the free Remoting components for Flash (basically a library of AS files).

  3. Write methods for your application server and write scripts in your Flash apps to trigger those methods.

Of course, when you deploy your app it will also need access to a Remotingenabled server. Most likely this means your web server has an application server running adjacent to it. If you don't already have a deployment plan, install ColdFusion MX 6.1 as well as the Remoting components for Flash (both available at www.macromedia.com).

How it Works

Figure 7.1 shows the sequence of events for a Flash app accessing a remote method (that is, a method on your server).

Figure 7.1. The sequence Flash Remoting follows .


It all starts and ends with Flash. Flash makes a request and sends optional parameters to the remote method; the method processes the request by either triggering subsequent actions (maybe sending an email or adding a record to a database); finally, an optional message containing data is sent back to Flash, which you can process as you want. Because this is asynchronous (meaning Flash won't just freeze while it waits for a reply), you'll first define how you want Flash to handle the response and then trigger the method. The entire process is similar to how you can trigger functions within a Flash movie.

One part of this description that I left out is about preparing and processing data. That is, I didn't explain how Flash must first prepare the data it sends as a parameter, how that data arrives at the remote method, how the remote method prepares data it's going to send back, or how that data arrives back inside Flash. I didn't explain it because it doesn't matter! Primarily, this is just part of your design decisions. If you want to send a generic object containing properties for name , age , and telephone and expect the remote method to extract values for each property and insert them into a database, for example, it's up to you. The great part is that you can pass any data type you want. Although the ColdFusion language doesn't include generic objects, it does have the struct data format, which is basically the same thing. The syntax varies, but your application server and Flash don't need to translate anything. It's almost as though the two sides can speak their own (different) language and it gets translated over the Remoting channel.

Later in this chapter you'll see how you can forgo Remoting and access remote functions that are built as web services. The reason to consider Remoting, however, is that the AMF protocol used is way more efficient than SOAP (the protocol used by web services). SOAP is just a particular form of XML. As such it includes additional tags that all add up to a larger file ( roughly four times as large). In the case of AMF, it's an optimized binary format. They both travel over HTTP, but the same data as AMF will always be smaller than SOAP. In addition, AMF can do tricks such as paging so that huge data sets effectively stream in bite-size packets.

The only legitimate gripe against Remoting is that it costs money (at least for non-ColdFusion servers) and it uses the proprietary AMF protocol. When you make the effort to expose your server-side method as a web service, you're producing something that can be used with anything else supporting SOAP. Making a server-side component that works with AMF limits it to Flash Remoting. It's not quite that bad with ColdFusion because the same code used for Remoting can be used by your regular ColdFusion pages. Ultimately SOAP is more universal. Although web services (that is, SOAP) are all the rage, you can't ignore the fact this standard is necessarily wordy.

Basic Remoting

There are always two sides to a Remoting callFlash and the method on your application server. Flash has to set up the gateway over which data will travel, make a request, and define how to respond when an answer is received. The server-side method is like any function: It has a name, it specifies expected parameters, and it includes code to carry out the intended effect, including preparing and sending back a return value.

I use the starter script in Listing 7.1 for any Remoting application.

Listing 7.1. Basic Remoting Script
 1 #include "NetServices.as" 2 #include "NetDebug.as" 3 myResponder=function(){ 4 this.onResult=function(data){ 5 trace("data returned is " + data); 6 } 7 this.onStatus=function(info){ 8 trace("status is :" + info .description); 9 } 10 } 11 if (inited == null){ 12 inited = true; 13 NetServices.setDefaultGatewayUrl(/books/1/478/1/html/2/ 14 "http://localhost:8500/flashservices/gateway/"); 15 myGateway = NetServices.createGatewayConnection(); 16 myService = myGateway.getService(" path .to.cfc"); 17 } 18 //trigger: 19 myService.doMyFunction(new myResponder(),"param"); 

The first line loads the NetServices library of ActionScript. The second line loads code for when using the NetConnection Debugger (available from Window, Other Panels). Then the " responder " object is defined. This handles all responses from the remote method. Inside you can see two event handlers. On line 4 onResult triggers when data is returned as expected. I happen to call the parameter data , although what's important is that all data is returned as a single parameter. Line 7 shows onStatus , which only triggers when an error occurs. Notice the parameter received is a generic object with a description property. That parameter includes other properties ( level, code , and details ), but description is the most digestible.

Finally, lines 13 through 16 only need to execute once (so I'm just using inited as a flag). Line 13 specifies the URL where Flash Remoting is installed. It's not like there's really a folder that matchesit's just always specified as flashservices/gateway (under your web site's root directory). Line 15 creates a gateway and stores it in the homemade myGateway variable. Then, line 16 uses getService() to point to the actual server-side method and stores this reference in the myService variable. In this case, there really is a file. The syntax uses dots rather than slashes , so path.to.cfc means that inside the root web site there's a file called cfc inside the to folder, which is inside path . That file contains the server-side method.

After everything has been set up (that is, we have a responder and a service), you can trigger a remote method (as shown in line 18). This example points to a function named doMyFunction() and passes "param" as the first parameter. Well, actually, it shows up in the second slot because Flash wants the responder object in the first slot. If the doMyFunction() were in the Flash file, we would just say _root.doMyFunction("param") . Because the function is remote, however, I use the previously defined myService and sneak an instance of the responder object in the first parameter slot.

That's the Flash side of Remoting in a nutshell . It really is pretty easy. Let me make a few additional notes before we look at some samples. I said the data returned (the parameter data on line 4) contains everything returned from the remote method. That is, if the method returns an array, data is an array. If the method returns a string, it's a string. In the case of query results, you get an array full of generic objects, each with matching property names . It just depends how the remote method is designed.

The same data type issue applies to the data you send. In the example, line 19 shows I'm passing a string ("param"). I could just as easily pass an array or object or number.

Finally, line 19 triggers the remote call. You might not want to do this right at the start of your app. Perhaps you want users to type in their name, and then you'll pass their name back to the remote method. You can put that trigger anywhere you want. In addition, you can even trigger the same function repeatedlyor before the results from the first call arrive back. Because it's asynchronous, you need a way to associate returned data with the right trigger. Maybe I have a remote method that can look up only one product's price at a time, but I still want to give the user a way to request several in one move. To solve this, you could change the responder to expect and track a parameter:

 myResponder=function(id){ this.id=id; this.onResult=function(data){ trace("data for "+ this.id + " is " + data); } } 

Then, pass a unique ID for each trigger:

 myService.doMyFunction(new myResponder("request 1"),"param"); myService.doMyFunction(new myResponder("request 2"),"param"); 

Remoting Example

Here's a simple example that relies on a sample server-side method convert() that gets installed with ColdFusion. It's sort of cheating to show you this because you just have to believe the server-side method performs as described. (You'll see the server side in a minute.)

I have a button ( my_btn ), a text field ( result_txt ), and an input text field ( input_txt ), as well as this code in the first frame:

 1 myResponder=function(){ 2 this.onResult=function(data){ 3 result_txt.text=data; 4 } 5 } 6 7 my_btn.onPress=function(){ 8 myService.convert(new myResponder(), "F", input_txt.text); 9 } 10 11 NetServices.setDefaultGatewayUrl(/books/1/478/1/html/2/ 12 "http://localhost:8500/flashservices/gateway/"); 13 myGateway = NetServices.createGatewayConnection(); 14 myGateway.getService("cfdocs.exampleapps.cfc.tempconverter"); 

After installing ColdFusion, I found a server-side method called tempconverter.cfc (inside wwwroot /cfdocs/exampleapps/cfc )hence the parameter in line 14. Notice that you don't include the .cfc file extension and that this particular method happens to be in a folder called cfc.

Take my word that the tempconverter file contains a method called convert() that accepts two parameters: the scale ( "F" or "C") and the temperature you want to convert. Line 8 is where I trigger that function and pass two parameters. I should disclose that I included the onStatus() event while troubleshooting this code.

Writing the Remote Method

The temperature conversion example just mentioned used a sample file, so I didn't have to first create a remote method. Obviously, you need a remote method before you can call it. We'll look at a quick ColdFusion example (and, in fact, you're welcome to check out the tempconverter.cfc file). However, it makes sense to keep Flash and the server side separate. In fact, I completed an entire project using Remoting where I stayed in Flash and the ColdFusion expert stayed in ColdFusion. It's a perfect separation of duties . We just communicated details including the method names, what parameters they expect to receive, and what data types they returned. I'm not just saying this to avoid covering the server side, but rather to point out this separation is what Remoting is all about. You get access to remote methods, but you don't have to know how they were built.

Here's an absolute minimum ColdFusion component (CFC):

 1 <cfcomponent> 2 <cffunction name="sayHello" access="remote" > 3 <cfreturn "hi there"> 4 </cffunction> 5 </cfcomponent> 

If you know how to make a CFC, you'll notice two things. First, the preceding example avoids many optional tags that provide extra information. Second, the tag access="remote" is the one element that applies only to Flash (and it's required for Remoting). You can see the whole thing is a cfcomponent and there's one nested cffunction . A single component file can have additional functions. The method Flash would trigger in this example is sayHello() . Notice cfreturn is where the value "hi there" gets sent back to Flash.

There's a lot more you can do in CFCs. You can accept parameters, perform more elaborate procedures (such as querying or writing to a database), and return more complex data types such as arrays and structs (equivalent to Flash generic objects). The best example file I can recommend is Macromedia's free noteboard example available at www.macromedia.com/devnet/ria/note_board/ and shown in Figure 7.2. It comes with the Flash source files, the CFCs, and an accompanying article.

Figure 7.2. The noteboard sample is a working application that uses Flash Remoting to edit a database.


Remoting Tips

Although Remoting is very simple, the potential is much greater. However, you do need to be aware of a few details, covered in the following sections, as you embark on using Remoting in your app.

Complex Data

As mentioned previously, any data type can pass over Flash Remoting. This includes generic objects and arrays. It also includes arrays full of objects. Interestingly, when your remote method returns the results of a query (that is, all the records in a database table that match a particular criteria), it arrives in Flash as a generic object with several additional properties. It's called a recordset. The structure may not seem particularly logical, although you can easily dig in and extract the parts you need. Figure 7.3 shows both original database structure as well as the data returned to Flash (when the query returned all records).

Figure 7.3. The original data in Access (left) arrives in Flash via a query as a recordset with several additional properties.


Notice the array of objects that appear under the items property. The structure of a recordset is important for a few reasons. First, you commonly need to receive a set of records. Also, you may want to parse through the results. Finally, recordsets are really easy to use with components becausealthough a recordset doesn't fit the formal definition of a dataProvider you can use it as a dataProvider and it works out great. For example, I could place a List component onstage ( myList ) and use myList.dataProvider=data inside the myResponder's onResult event. Finally, check out the available methods for the recordset. There are fancy features such as the DataGlue object for rearranging columns . Check out the methods available under Flash Remoting in your Actions panel.

The other data types such as arrays and generic objects are more straightforward.

When to Use Remoting

Designing an app that uses Remoting is nearly the same as designing a utility function. That is, you have to decide which parameters the function will accept, what the function will do, and which values it returnsif any. But the decision whether to use Remoting is high on many people's list.

The reason to reach for Remoting is simply when you want access to something outside Flash. Most often this is a database. Application servers include methods to access and modify databases.

Another reason to use Remoting is because you want to get the data out of Flash. After a user completes a survey, for example, you can send all that data to the application server and have it store the data for safekeeping. Of course, this could mean writing it to a database, but it could also just forward the results in an email to someone.

Finally, a great reason to use Remoting is to recycle or mirror existing code. Suppose, for instance, that you're already using an application server to produce a sophisticated HTML-based app. If the code is modular enough, you should have little trouble converting it to work with Flash Remoting calls. This way you can convert your HTML front to a Flash front without rewriting all the code. In addition, if you want to run both an HTML and a Flash version of your app, you can do it with the underlying code.

Many of these "reasons to use remoting" are also "reasons to use web services/SOAP." Remoting does have a distinct performance advantage. In addition, it's free with ColdFusion. Also, you don't need Flash Pro. The only downside is that it's not a standard format like SOAP.

[ LiB ]  

Macromedia Flash MX 2004 for Rich Internet Applications
Macromedia Flash MX 2004 for Rich Internet Applications
ISBN: 0735713669
EAN: 2147483647
Year: 2002
Pages: 120

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net