Building Flash clients for Web Services with Soap and Flash MX
Topics Covered
- Interacting between Flash and Web Services
- Using the new Load Vars Object in Flash MX
- Using Components to simplify the process
- Using Styles to easily change the look of your components and text fields
- Why use Soap based Web Services
Overview
In this tutorial we are going to build a Flash Language Translator. The language translator will be able to translate between any two languages. The Language translation service was chosen because it's basic, yet provides an easy way to get into web services and is something you can use on your site right away. The tutorial also shows the basic's of using components in a Flash movie and loading dynamic content into them.
First lets take a look at what a soap based web service is. It's easy to get lost in all the technical definitions of web services - so we take a very basic approach. A web service is any server side logic that can be accessed over standard network protocols (HTML, XML, SMTP, etc). So that being the case - web services in general are nothing new. What's new is the SOAP standard. What soap does is standardize the way messages are sent between a Client and a Service. Usually soap messages are sent to a server, which then invoke some application and returns the result. Well their are quite a few more use's but for this tutorial we'll leave it at that. A simple way for any programming language from any server, device, other application, etc - to communicate with any other server, device, application in any programming language.
We really don't need to spend any time on the details of what a web service is or does for this tutorial, as all we want to do is be able to use them to add additional functionality to a flash movie. We'll go into them a bit more as this progresses. First we have to take care of the Flash side of things. If you want to get an idea of what where building - you can do so here:
In the service directory or Or by itself. The actual service is provided by xMethods here.
So lets move on...
Setting up the Flash Client for the Language Translator
A Client in this case refers to the application that is displaying the result obtained from the service and handling the user input. In this case a string (paragraph of text) is sent from the Flash Movie, to the Service, and returned back to the Flash movie. The service translates the string from one language (for example English) to another language (for example German). So the result will contain whatever text the user entered in English with it's German Translation.
Adding the components to the Flash Client: We are going to use components to make development time a bit faster. The components are all part of the standard Flash UI Components. Two Scrollbars, one combo Box, and one push button will be used. We will add them one by one. You may want to open up the download associated with this tutorial and follow along with the completed FLA.
Let's add some scrollBars: Drag a scrollBar from the components window (In Flash -> Windows>Components). And place it in the movie. This will look like:
Give this component an instance name of "ScrollBarTop". By giving the component an instance name we can refer to it later in the ActionScript. At this point also create a text field right next to the Scroll bar component and give that an instance name of 'Input'. This can be seen below:
Notice that in the first image we specify the Target TextField as 'Input'. We then created a text field and gave it an instance name of 'Input'. This will associate the scroll bar with the dynamic text field named 'Input'. So the scroll bar will scroll any text that is in the Input text field if it's length exceeds the contents of the text field. The biggest difference here between Flash 5 and Flash MX is that we give the text field an Instance name (top left hand corner of properties box), and not a variable name. By giving Text fields an instance name we are able to treat them similar to Movie clips - and control all of their properties with Actions, instead of direct editing.
Add the rest of the components
We need to finish up by adding a combo Box, Push Button, and another text field and scrollbar for the output. This can be seen as follows:
Each Component instance name is shown in the above screen shot. For example the combo Box has an instance name of 'comboBox', the bottom scroll bar has an instance name of 'ScrollBarBottom', and the push button has an instance name of 'submit'. We now have the basic setup done - after this we use ActionScript to change the colors, properties, and actions of the components. No further editing of the FLA is needed unless you want to add some background graphics in.
Adding some Style to our components
Wow - those components sure are ugly. We'll where going to fix that up right now. We are going to use the FStyleFormat associated with each component to change the look of all of our components at once. This is really similar to using CSS (Cascading Style Sheets) in HTML. Here is what the code for changing the Style of all of our components looks like:
// Create a new Format - that we can apply to multiple objects/components later. formStyleFormat = new FStyleFormat; formStyleFormat.scrollTrack = "0x000099"; formStyleFormat.highlight = "0xffffff"; formStyleFormat.highlight3D = "0x000033"; formStyleFormat.arrow = "0xffffff"; formStyleFormat.face = "0x0066FF"; formStyleFormat.background = "0x0066FF"; formStyleFormat.shadow = "0x000099"; formStyleFormat.darkshadow = "0x000033"; formStyleFormat.selection = "0x000033"; formStyleFormat.textColor = "0x000066"; formStyleFormat.textBold = false; // Add a listener to each one and Apply the Changes to the Components. formStyleFormat.addListener(ScrollBarTop, ScrollBarBottom, comboBox, submit); formStyleFormat.applyChanges();
What this is doing is setting up a standard Style and applying it to all the components. This makes things easy because you can copy and paste a style/format you come up with into any other movie you want - and the components will be formatted the same.
Formatting the text fields: We can do a lot more with text fields now that they have an instance name - and it doesn't really matter what properties we actually specified for the text field when creating them - as long as they are defined as such:
// Set up individual Text Area's (Input). Input.multiline = true; Input.wordWrap = true; Input.type = "input"; Input.background = true; Input.backgroundColor = "0x000099"; Input.border = true; Input.borderColor = "0x003300"; Input.html = false; Input.textColor = "0xffffff";
We can reference all of the text fields properties as above - as long as they have an instance name associated with them. We also change the properties of the 'Output' text field in about the same way - with the main exception being that we set the .html property to 'true'.
One last part to mention is setting the text on the push button, this is done with the code:
submit.setLabel("Translate Now!");
And that's about it for the Style's part of our form. All of the Formatting and Style's ActionScript is located in a layer called 'Styles' in the main flash movie. It's best to keep all of the style and formatting code on one layer so it's easier to find later on. Now we've only got one more component to work with and that's the combo Box which will list all of the available translation modes. So here goes:
The combo Box:
We keep all of the available translation modes in a separate text file from which we load into Flash and populate the combo box with. First we need to create a text file with the necessary data. How this text file is formatted is the most important aspect of populating components with external data sources. So here's a look:
&mode0=en_fr&desc0=English to French& &mode1=en_zh&desc1=English to Chinese& &mode2=en_de&desc2=English to German& &mode3=en_it&desc3=English to Italian& &numModes=4&
Ok what the data contains is not as important as how it's formatted. In the download we have a text file with all of the modes contained in it. In this example we are just using 4 possible modes so it doesn't take up to much space. Notice how the numbers work, after each mode and desc variable their is an increasing incremental number, ie 0,1,2,3. The mode in this case is a string that for example looks like 'en_fr' indicating English to French, that is all that is really needed. We added the description (desc) variable as a way to visually display the short hand.
Next we have to load this text file (called Modes.txt in the download) - into the movie. The ActionScript for that will look like the following:
// Create a New LoadVars Object
myModes = new LoadVars();
// This Tells the Flash movie What function to invoke when the Load Vars Is complete.
myModes.onLoad = addModes;
// Find the Text File - Load it - after which the function addModes is invoked.
myModes.load("Modes.txt");We are using the LoadVars Object in this case to load the text file. This is useful because we can use the .onLoad function associated with the Load Vars object to wait for the data to load - and then invoke a function when it's done (addModes). That function will populate the combo box with the data from the Text file - and looks like this:
function addModes() {
// Loops through the number of listings in the text file and sets them up as nodes.
for (i=0; i comboBox.addItem(desc, Modes);
}
}The comments in the script above should cover about everything. Basically we loop through each record in the text file and add an item to the combo Box for each row in the text file. By creating a data provider for each we can assign as much data to each individual combo box item as needed. This function is found in the 'Functions' layer of the FLA that comes with the download. Some more examples and downloads for this type of thing can be found here: flash-db.com/Components/
So with the combo Box set up and all of the component styles and formats set - we have something that looks like:
So now it's onto the interesting stuff.
Sending the data from the Translation script
First we have to add some ActionScript to let the movie know what to do when someone clicks on the 'Translate Now' Push button component. This is shown as follows (remember the push button was given an instance name of 'submit'):
// Set the change Handler function for the push button named 'submit'
submit.setClickHandler("onClick");Now that we have that set up - we add the 'onClick' function. This function will locate all of the necessary data in the movie and send it to the script which handles the translation.
// Function to handle what the movie does when some one selects a mode and clicks the push button.
function onClick(){
// Grab some values from the ComboBox and the Input Text Field.
sendMode = comboBox.getSelectedItem().data["mode"];
sendText = Input.text;
// Load New vars.. (this is the Load Vars object that will send and receive the response from the server,
// ie - sends 2 variables to a PHP script - then returns an Object that has the translation.
translate = new LoadVars();
// Add Vars to translate Object.
translate.Mode = sendMode;
translate.sourceData = sendText;
// This Tells the Flash movie What function to invoke when the Load Vars Is complete.
translate.onLoad = addTranslation;
// Find the Text File - Load it - after which the function addTranslation is invoked.
translate.sendAndLoad("Translate.php", translate, "POST");
}Ok what where doing here is getting the selected mode and the text entered by the user in the text field with instance name 'Input'. Then creating a new Load Vars object and sending it to the script which handles everything else. The important thing here is that we load up the Load Vars object with all of the variables we want to send to the script. In this case we are naming the new load Vars object 'translate' - so we add two variables to the Object in standard dot syntax ie (translate.Mode = sendMode). So now the Translate Object has 2 variables associated with it - Mode and sourceData. Mode is the language conversion we want to do, and sourceData is the user entered text to translate. We then use the sendAndLoad method to send these variables via "POST" to the receiving script. We also set an .onLoad function (addTranslation) to handle what's returned.
Recieving the data from the Translation script
So before we get to the Server side of this, we set up the function addTranslation.
function addTranslation() {
Output.htmlText = translate.soapOut;
}The Text field with instance name 'Output' receives the results of the script (the translated text). The same Load Vars Object is referenced in this case (translate) - and it now contains the resulting data. Make sure to specify the output sent to the 'Output' text field as HTML text. This is done by using the property - .htmlText. So now the Output text field knows that it is receiving HTML text and will format it correctly.
So now the Flash Client is set up and ready to send and receive the data.
The Server Side
Flash can't load data from an outside domain. This being the case we need to use some type of script that acts as a proxy and also handles all of the details of sending and receiving soap based messages. We have quite a few options available to use for this step. Their are literally hundreds of different Soap toolkits that can handle this part for us. The most relevant ones would be the MS .net soap toolkit from Microsoft, Flash Remoting which requires Coldfusion or a special component (Salsa) installed on your server, and of course either of the PHP soap toolkits. A soap toolkit is basically a couple of classes and functions that handles all of the details of sending and receiving soap based messages. So what did we choose for this tutorial, well of course one of the PHP toolkits.
Nusoap/SOAPx4: In this example we are going to use Nusoap (aka SOAPx4). We are using Nusoap because it only requires 1 php file to be placed anywhere on any server. This also allows us to use web services with any computer running PHP. By any I mean any - You can build your application on any windows, Mac, Linux desktop and deploy it on any Windows, Mac, Unix, Linux Server. So it's tough to beat a setup that only requires 1 file on any server. Their are no special installation or server setup worries, their is nothing to buy, and you can build your own Soap based web service just as easily as sending a soap message. The main disadvantage of Nusoap is that at the time of this writing it is not as mature as some of the other toolkits (.Net) and has some growing to do. But it works for any web service and great for the example so we'll let it go at that. So here goes:
First: You will need to place the Flash Client we just created, a file called 'nusoap.php' (in the download), and the following code in the same directory on your server. In the future you can change around the paths - as only 1 nusoap.php file is needed for all clients. Also you might want to experiment with setting it up so that the path to WSDL file and operation/method to be used - is sent from the flash movie instead of being specified in the script, this creates a more generic soap client - but generic solutions can also cause problems and are limiting).
&The first 2 lines are needed to indicate the variables coming into the script from flash via 'POST'. The next line includes the Nusoap Soap toolkit classes needed for the details. Then we specify the input parameters, in this case translation mode and sourcedata are required. Then we need to create a new soap Client. In this example we specify the path to the WSDL file (Web Service description language), the WSDL file describes the service that we are going to use - and indicates all of the important parts in an XML format. The WSDL file is parsed by the toolkit and used to call the service (among other things). Usually a Service has a couple of available operations or methods in which you can use - these are also specified in the WSDL file. In this case we are using the 'BabelFish' operation/method. When we call this script - that operation (basically a function on some other server) is invoked and a result is returned. The variable $result holds the result and is passed back to flash on the last line. This is a simple case - in most case's the $result will hold an array or other more complex structure's (like with Google's API) - that needs to be parsed before it's sent back. Usually it's only 1 or 2 additional lines though.
Well this tutorial is not on WSDL so I'll spare the details - but usually the most important part of the WSDL file is the location of the EndPoint - the Endpoint is where the service actually/physically resides. In the above script you can skip the middle WSDL file and indicate the exact endpoint if wanted.
To visually see the WSDL file - you can use the following Tool, which is a Flash application that Parse's a WSDL file and describes everything in that file in an easy to read/use Flash interface - the link to that for the BabelFish service is as follows:
WSDLInspect.php?WSDLIn=http://www.xmethods.net/sd/2001/BabelFishService.wsdl
Well that's about it. We'll finish up with some links to additional resources and a few closing words.
Conclusion and additional resources
Now you can create a client for the Babelfish translation service, but this is only the start. Their are hundreds of other similar services out their that you can use to add value to your Flash movie. Anything from Stock Quote Lookups, to services that return weather data, to credit card processors. And their all available to you and your Flash movie. Services such as these in general are good for Flash programmers and designers because they provide a way to obtain data in a format that is not bound to HTML - it's meant for any application on any server, device, or other application - so it's easy to use in your Flash movie. Hopefully many other companies will offer their services as Soap based services in the future, so all of us Flash programmers and designers can use their data. I'm sure as soap based web services gain in popularity costs will be added to using these services, for example each time you translate some text it cost's you 1 penny or so. But that's expected since they are providing a service that brings value to your Flash movie, and their are also costs involved in hosting these services. In the future it will become more and more interesting combining all these different services into unique flash clients that where not possible before.
One thing to remember is that their is quite a bit of hype surrounding web services right now - but in the near future they will be as common as search engines on the internet. So learn the basic's and try not to spend any money on things that really are not needed - especially at this point in time.
Resources:
- The Flash-db Web Services Directory: A directory with all Flash clients
- xMethods.com: One of the first and still the best directory of Web Services
- remotemethods.com: Decent directory of Web services, although it tends to mirror xMethods and not as much attention is paid to the listings their.
- Salcentral.com: Another directory - they have something going on where they host an intermediate layer between the actual services and the site. Not sure what to think of Salcentral at this time, but they do have a large selection as well.
And that's about it.
Author: Jeff Hill
» Level Advanced
Added: : 2002-08-19
Rating: 6.56 Votes: 9
Hits: 1987» Author Jeffrey Hill is a freelance web developer from Boulder, Colorado. He specializes in creating and developing dynamic database driven Flash content, applications, and content management systems. Specialty's include SQL, PHP, Perl, XML, web services, and Flash clients for web services. » Download Download the files used in this tutorial. Download (251 kb)
discuss this topic to forum
