You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion, Adobe Flex

ColdFusion: Article

Flash Remoting: An Alternative Approach

Bucking the conventional wisdom with CFM files

Although an "undeniably excellent" product, Flash Remoting presents a few problems. This article offers solutions in the areas of authentication and error-handling.

Most people who have experienced Flash Remoting seem to be impressed with it. I, for one, couldn't help but be impressed by the demonstration Macromedia gave at one of their seminars. (See reservations.broadmoor.com for an excellent example.)

Building on the component structure provided by ColdFusion MX, Flash Remoting promises the world: a platform-independent rich client that interacts seamlessly with the server. Using Flash Remoting developers can produce dynamic clients that encompass more functionality per page than was previously possible. Since the Flash client remains loaded on the client's machine, and all that is sent back and forth is the data, less bandwidth is required, and the load on the servers is lessened.

Sounds perfect! But every silver lining has its associated cloud, and the same is true of Flash Remoting. Whereas it is undeniably excellent, Flash Remoting does present its own problems. The thing is, can we get around these problems in a way that makes Flash Remoting still worth using?

How do we use this wonderful product? Well, conventional wisdom says that we use components (CFCs) on the server to collect together related functions, and call those functions directly from the Flash client. What's wrong with that? you ask. Well, there are two main reasons why I did not take this approach.

  1. I wanted a central authentication system that just worked without my having to add code to every function to call the authenticator.
  2. I wanted to handle errors such as message timeout, authentication errors, wrong parameters, or just about anything else in a sensible manner so that I could pass back useful error results to the client.
So why couldn't I achieve these results with CFCs? Originally I thought I could, and maybe sometime in the future (when suitable modifications have been made to ColdFusion) I will be able to, but right now I can't.

If I use an Application.cfm file, then I should be able to add my authentication there and halt the call to the CFC function if it is not authenticated. Macromedia provides a really useful function, getHTTPRequestData(), which should show the contents of the message sent to the server from the client. The problem is, it doesn't work. It supplies some information. However, some of the data that I need to access (which function was called, what parameter values were provided) is simply not available.

Without knowing which function was called, I cannot decide whether or not authentication is required. (I did not require it for every function, as some parts of the site are accessible without logging in.) Even if I did authenticate for every function, I cannot access the parameter values, so I can't access the username/password. It's possible that I could obtain the values that I need by directly accessing structures within the Java factory, but I am reluctant to use such undocumented features on critical projects, as they may not be there in future versions.

Therefore, I'm stuck with putting the authentication inside each and every CFC <function> tag. The thing I really hate about this is that if another developer comes along in the future and adds a function but forgets to add the authentication code, then we have a security problem. To my mind, this is simply unacceptable.

The other thing I wanted was to be able to trap errors and return sensible error messages to the client. <cferror> in Application.cfm would seem to do the trick; but, alas, no. When calling a CFC function, a <cferror> is ignored.

What about <cftry>/<cfcatch>? The problem is that we can only put these inside the <cffunction> tags, which means they won't trap errors such as missing or mistyped parameters. Also, as with putting the authentication inside each function, we have the problem that if a future developer forgets to add this code, then we lose our error trapping.

The Silver Lining
Okay, enough of the cloud! Where's that silver lining I mentioned earlier? Well, it comes in the form of CFM files. If you delve into the ColdFusion documentation you will find that not only can you call functions within CFCs via Flash Remoting, but you can also call code in a CFM file as if it were a function.

But who would want to put each of their functions into separate CFM files? Not me, for a start! When I said that the answer "comes in the form of CFM files" I actually meant "file," not "files." What I did was to create a "gateway" CFM file that accepts calls from Flash. This CFM file contains all the functionality needed to decide whether or not to authenticate, call the authenticator if required, invoke the required function (in a separate CFC file), and trap any errors by wrapping the whole thing in a <cftry> tag.

The main part of the server gateway code (see Listing 1) looks like this (the code for this article can be downloaded from www.sys-con.com/coldfusion/sourcec.cfm):

<cfif authenticated>
	<cfinvoke component="#flash.params[1].module#"
		flash.result = structNew();
		flash.result.status  = false;
		flash.result.result  = "Not authenticated";

This is wrapped in a <cftry> tag to catch any errors, such as an invalid module or method name, or missing required parameters.

We also pass back the module and method name so that our Flash client knows which message is being replied to.

<cfset flash.result.component = flash.params[1].component>
<cfset flash.result.function = flash.params[1].function>

First we call our authenticate function to do the usual username/password check and return a true/false value.

If we pass the authentication test, then we try to invoke the function in the component requested by the Flash client. If that function does not exist, or we pass it the wrong parameters, or if something goes wrong that is not trapped within that function, then the error is caught here courtesy of our <cftry>/<cfcatch> tags. If we did not trap it, then a <function>_Status message containing information about the exception will be returned to the Flash client. By trapping the error, we can instead send more relevant information back to the client.

There are many more things we can do in our CFM file to make our lives easier, and I'll cover some of them later, but first let's consider the Flash client.

The Flash Client
In order to communicate with the server from Flash, we need to define a connection to the gateway. For this example, my serverRequest.cfm is located in a directory called "client" within the Web root directory, and I'm using the Web server provided with ColdFusion. I'm sure you've all seen code like this:

#include "NetServices.as"

gatewayConnection = NetServices.createGatewayConnection()
remotingService = gatewayConnnection.getService("client", this)

We need a function to prepare our remoting call. This will add the username and password to the parameters prepared for the function call.

function serverRequest(params)
    params.username = _global.username
    params.password = _global.password

We need to be able to handle the results, which will be returned to our Flash function, serverRequest_Result(). This function will check the status of the result, calling a specific handler function if the call is successful, and producing some tracing if it is not.

function serverRequest_Result(result)

   switch (result.status)
    case -1:
trace("E R R O R : Authentication error - need to login (again)");
   case "0":
trace("E R R O R : " + result.result);

   case "1":
trace("R E M O T I N G : Flash remoting call returned a success
targetFunction = result.component + "_" + result.function + "_Result";

The following code shows a typical invocation. We are calling a function, "getPageTemplate", from a component called "coursePlayer". We are passing two parameters to this function. Note: Because we are using argumentcollection="#flash.params[1].params#" in serverRequest.cfm, we must pass the params parameter, even if it's an empty structure.

flash = new Array();
flash.component = "coursePlayer";
flash.function = "getPageTemplate";

flash.params = new Array();
flash.params.param1 = "Hello";
flash.params.param2 = "World";

The following code shows our function, which is called if we have a successful reply.

function coursePlayer_getPageTemplate_Result(result)
   trace("coursePlayer_getPageTemplate_Result called")

We now have a ColdFusion CFM file that acts as a gateway to our main functions (located in various CFC files) and that centrally controls whether or not authentication is required, and if so, handles that authentication. The CFM file also manages error trapping and returns useful errors to our Flash client.

The Ramifications of #include "NetServices.as"
Now let's think a little more about our Flash client. We've all used this line of code (see Listing 2):

#include "NetServices.as"

But how many of us have stopped to think about what it does - besides the obvious of handling the remoting communication? Since the remoting is pretty much taken care of, perhaps the most important thing for us to consider is that it adds 4.5KB to our SWF file.

Who cares, you ask? Well, if you create your Flash client as a single huge movie clip, then not you. On the other hand, if, like me, you prefer to split your client into smaller parts, then read on.

Hey, 4.5KB is not that much....Well, let's put in some code to add some authentication to the message. This brings the communication code up to 6.5KB.

So what's the problem? Well, if you just add "#include NetServices.as" to each of those movie clips, then you add 6.5KB to each one. If your client consists of 50 movie clips, then you've added over 300KB. This is rather a lot, so what can we do about it?

The obvious thing is to add this code only to our root movie, using calls like:


That'll do it. Problem solved. End of article. Bye, see you next time. Hang on, maybe there's more than meets the eye here? Rather than doing that sort of call, I created a function in my root movie to handle it for me.

function serverRequest(params)
   params.username = _global.username
   params.password = _global.password

Now I don't need to worry about adding the authentication information to my functions; it's done for me. So if we go this route, won't all the remoting call results be sent back to the root movie? Yep. So how does the root movie get the results back to the movie that originally made the call? We use:

Flash.path = targetPath(this)

This function returns a string that represents the calling movie clip's position in the hierarchy. Say we have a movie called "outer.swf". Into this we load a movie clip called "middle.swf", and into that we load "inner.swf". Inner.swf wants to make a remoting call, so it makes a call to targetPath(this), and gets back "middle.inner". The movie clip that wants to send the remoting call calls this first, and passes the result as a parameter (path), which gets sent on to ColdFusion, which passes it back in the return message. When the remoting result is received in the root Flash movie, it invokes a function:

function serverRequest_Result(result)

Using this path parameter, the result function can route the results back to the movie clip that made the call.

targetMovieClip = this
targetPath = result.path.split(".")

// Loop through our list of movie clips, building targetMovieClip up into a
reference to the target move clip

for (i=0;i<targetPath.length;i++)
   targetMovieClip = targetMovieClip[targetPath[i]]

targetFunction = result.component + "_" + result.function + "_Result"

This calls a function <component>_<function>_Result in the target movie clip. Component and Function are also returned from ColdFusion to enable this routing. We simply add the following line of code to serverRequest.cfm:

<cfset flash.result.path = flash.params[1].path>

What other useful features can we add to our remoting interface? A fairly common problem is clients losing connection to the server. Either the server fails, or more often, the client loses the Internet connection. We could let each part of our client deal with it, or better still, we can add a central timeout handler.

What we need to do is make note of the function calls that are sent to the server and check them off as they are responded to. If we don't get a response, then we can deal with it. In this example, we are going to pop up an information panel to tell the user that the server is not responding and ask if he or she wishes to retry or not. If the user chooses to retry, then all the messages that were not responded to will be re-sent. After we have done this, if we do eventually receive a response from the server to the original messages, we'll just discard them. Of course you can adapt and change this handling. Maybe you'd prefer to accept the original response and trash the response to the duplicate message.

First we need to make a copy of the message that we are sending. To do this, I've added the following function to RemotingSetup.as:

function RemotingMessage(params,messageID,secure)
    this.component = params.component
    this.function = params.function
    this.path = params.path
    this.params = params.params
    this.timerID = setInterval(messageTimeout,timeoutPeriod,messageID)

and the following declarations:

// Used to record messages sent to the server
var messageID = 1
var sentMessages = new Array()

// Used to hold messages that have failed authentication, or have timedout,
// and are awaiting resubmission.

var queuedMessages = new Array()

We now have a counter to provide a unique ID for each message, an array to hold a list of messages that we have sent, and a second structure to hold a list of messages waiting to be re-sent. I need to add two lines of code to the serverRequest function in order to pass the message ID through to the CF server, and to save this message in the sent messages array:

params.messageID = thisMessageID

_root["sentMessages.message_" + thisMessageID] = new

Three more functions are required in RemotingSetup.as:


The messageTimeout() function is invoked when the setInterval timer expires. It removes the message from the sentMessages array and adds it to the queuedMessages array. Then it opens a pop-up requester to alert the user. If the user elects to retry, then resendQueuedMessages() re-sends all the messages in the queue, and clearMessageQueue() is used to abort, resulting in failure messages being returned to the originator of each of the messages in the queue. That way no function is ever left hanging, waiting for a response.

The last thing we need to do is add a few lines of code to the serverRequest_Result function:

messageData = _root["sentMessages.message_" + result.messageID]
delete _root["sentMessages.message_" + messageID]

This clears the timer and removes the message from the sentMessages array. If the message has already timed out, then messageData will be undefined and we just discard the message. If it is not, then we deal with the message as normal.

As we are now keeping a copy of the message in the Flash client, there is no need to pass information such as the path to the CF server since we can retrieve it from our new data stored in the sentMessages array.

We now have a central handler for Flash Remoting messages that will gracefully handle a loss of communication to the server, giving the user the option of resending any messages for which a response was not received. When responses are received, they are routed to whichever part of the Flash client initiated the communication.

What the Client Doesn't Know...
Before we finish, let's put our new message queue to one more use. As I mentioned earlier, some functions in my project require the user to be logged in, others do not. Obviously, the server knows which are which, so why worry about programming your client to know? Why not just let the client request a restricted function without having already forced the user to log in?

If the client requests a restricted function, the function call will fail, and the client will receive an authentication failure response. Rather than pass this failure back to the calling function, we can simply pop up a login box for the user, and ask him or her to log in. We can then automatically resend our failed request, but this time, with a (hopefully) valid username/password. We should then receive a successful response, which we can pass back to the calling function. It receives the information it requires without having been aware of the authentication failure or the re-sent message. See Listings 3 and 4 for the full code.

More Stories By Ian Bale

Ian Bale is co-director of Celtic Internet ltd. (www.celticinternet.com), a UK-based software engineering and consultancy company. Ian has worked as a consultant since 1989 in both the telecom and Internet industries.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

IoT & Smart Cities Stories
The deluge of IoT sensor data collected from connected devices and the powerful AI required to make that data actionable are giving rise to a hybrid ecosystem in which cloud, on-prem and edge processes become interweaved. Attendees will learn how emerging composable infrastructure solutions deliver the adaptive architecture needed to manage this new data reality. Machine learning algorithms can better anticipate data storms and automate resources to support surges, including fully scalable GPU-c...
A valuable conference experience generates new contacts, sales leads, potential strategic partners and potential investors; helps gather competitive intelligence and even provides inspiration for new products and services. Conference Guru works with conference organizers to pass great deals to great conferences, helping you discover new conferences and increase your return on investment.
Poor data quality and analytics drive down business value. In fact, Gartner estimated that the average financial impact of poor data quality on organizations is $9.7 million per year. But bad data is much more than a cost center. By eroding trust in information, analytics and the business decisions based on these, it is a serious impediment to digital transformation.
SYS-CON Events announced today that Silicon India has been named “Media Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Published in Silicon Valley, Silicon India magazine is the premiere platform for CIOs to discuss their innovative enterprise solutions and allows IT vendors to learn about new solutions that can help grow their business.
We are seeing a major migration of enterprises applications to the cloud. As cloud and business use of real time applications accelerate, legacy networks are no longer able to architecturally support cloud adoption and deliver the performance and security required by highly distributed enterprises. These outdated solutions have become more costly and complicated to implement, install, manage, and maintain.SD-WAN offers unlimited capabilities for accessing the benefits of the cloud and Internet. ...
Founded in 2000, Chetu Inc. is a global provider of customized software development solutions and IT staff augmentation services for software technology providers. By providing clients with unparalleled niche technology expertise and industry experience, Chetu has become the premiere long-term, back-end software development partner for start-ups, SMBs, and Fortune 500 companies. Chetu is headquartered in Plantation, Florida, with thirteen offices throughout the U.S. and abroad.
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
DXWorldEXPO LLC announced today that "IoT Now" was named media sponsor of CloudEXPO | DXWorldEXPO 2018 New York, which will take place on November 11-13, 2018 in New York City, NY. IoT Now explores the evolving opportunities and challenges facing CSPs, and it passes on some lessons learned from those who have taken the first steps in next-gen IoT services.
Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...