The Communication ActionScript Objects

"Trojan horse" is one term that can be used to describe the Communication Objects in Flash MX and Flash Player 6. You see, Flash Player 6 was shipped with full support of these new objects before the Communication Server arrived. The Camera object could always connect to your camera. Local persistent SharedObjects could be used; however, this fact didn't even make it into the Flash MX online dictionary or manual. Even LocalConnection wasn't in the original documentation. Everyone got curious when they saw the new settings options and Privacy panel when a Flash application was right-clicked in Flash Player 6. The biggest question was, "What does the camera and microphone thing do?"

The Communication Server brought with it the ActionScript references for these objects. When you installed the Communication components into Flash MX, an entirely new set of ActionScript code hints and dictionaries were installed in the ActionScript panel's Toolbox under the heading Communication, as shown in Figure 12.1.

Figure 12.1. The Communication Dictionary can be found in the ActionScript panel's Toolbox (F9), or the Reference panel (Shift+F1).

graphics/12fig01.gif

Included in this tree, amidst the new Communication objects, are native Flash MX objects that do not require Flash Communication Server to be used. So the label "Trojan horse" is appropriate in a good way. Just when you thought you knew it all in Flash MX, you get another fix with the Communication Server.

Because this is the first time you've ever seen these objects, we'll step through them in some detail, but there isn't room to cover every feature here. Instead, Appendix B,"Macromedia Flash ActionScript Objects Quick Reference," details every method, property, and event for each Communication object.

Camera Object

The Camera object controls the Flash player's internal video capture driver. This driver accesses supported video sources attached to a client's computer, such as a web camera, a Firewire source, or supported screen capture utilities. The settings that can be controlled with ActionScript include frame size, frame rate, and bandwidth consumption. Limited control over the internal video compressor lets you also set the keyframe rate.

A great feature, even without the Communication Server, is the ability to use the Camera object to trigger events. That's right, you can use the camera input to monitor motion. When it detects movement (or a lack of movement), an event can trigger ActionScript to do something. When you add the Flash Communication Server to the camera feed, you can publish video to the server. This will make the camera feed recordable. You can also snapshot still images or record a series of still images captured automatically over time.

The key method to using the Camera object is Camera.get(), which tells the Flash player to access a camera attached to the client's computer. This method triggers the Privacy panel, informing the user that the Flash player is accessing the camera. You can also trigger this panel using the Security object, which will be discussed later in the chapter.

Exercise 12.1: Displaying the Camera

To display the camera on the Flash stage, you need an embedded Video object. Video objects are available from the Library panel, as shown in Figure 12.2. Let's do a simple exercise to display your web camera on your Flash stage.

  1. Create a new Flash document in Flash MX.

  2. Open the Library panel (F11), and click the Library panel pull-down menu (circled in Figure 12.2).

  3. Add a new video to the library.

  4. Drag the Video object to the Flash stage.

  5. Assign it an instance name of my_video in the Properties panel. Make sure you use a name with the suffix _video to enable video code hinting in the ActionScript Editor.

  6. Open the ActionScript Editor (F9).

  7. Click on Frame 1, Layer 1 in the Timeline, and add the following code in the ActionScript Editor:

    my_camera = Camera.get(); 
    my_Video.attachVideo(my_Camera);
    
  8. Save your document, and test your movie (Ctrl+Enter).

    When the movie runs, you will be prompted by the player to allow the Flash player to access your video camera. When you accept, you will see your camera on your screen.

  9. Try accessing the motion sensor. Add the following to set up the event handler:

    my_camera.setMotionLevel(10, 500); 
    

    This sets the motion sensitivity to 10 (out of 100) and the timeout to 1/2 second (500 milliseconds). If you are curious to learn more about this feature, refer to Appendix B.

  10. Add the following code, and then save and test your movie again:

    my_camera.onActivity = function(value) { 
    if (value) {trace("Someone is there");}
     else { trace("Come back and play");}
     };
    }
    

    When you test your movie this time, keep an eye on the Flash Output window (F2). Hold very still, and then move in front of the camera. When you move, you will see trace actions in the Output window. When you stop moving, the onActivity property is set to false and trace actions display in the Output window.

Figure 12.2. Add embedded video using the New Video item in the Library's pull-down menu.

graphics/12fig02.gif

The camera also has an onStatus event. This event is triggered when the user allows or denys access to the camera. You can overwrite the onStatus function to handle the information that will be returned with a simple script, like this:

my_camera.onStatus = function(infoObj){ 
trace("level: " + infoObj.level + "code: " + infoObj.code);
}

Two information objects can be returned: Camera.muted and Camera.unmuted.

You have already seen how to connect your camera to the publish stream in Exercise 7.4 in Chapter 7, "STEP 7: Streaming Video with NetStream()." It is as simple as attaching the Camera feed to the NetStream.

For a full list of the Camera objects, refer to Appendix B.For some tips on troubleshooting your camera, refer to the section on cameras and microphones near the end of this chapter.

Capturing Your Desktop as a Video Source

With third-party software, you can use the Camera object to capture a small window on your desktop as your video source. The Camtasia Recorder (see Figure 12.3) from TechSmith operates like a PC camera when it is in Live mode. The software is available for the Microsoft Windows platform only. To the Flash player, it appears as a standard Video for Windows capture device.

Figure 12.3. The Camtasia Screen Capture tool from Techsmith is available for the Windows platform only.

graphics/12fig03.gif

This means that you can use Flash to distribute a live feed of your applications or your desktop. The only limitation is that you are restricted to a 320x240 window area.

To select the Camtasia Video Capture Driver on your Flash player, access the player's Settings panel by right-clicking on the Flash player and choosing Settings from the menu. Select the Camera tab. If your Camtasia Recorder is installed correctly, you should see an entry in the Camera pull-down menu for the Camtasia Video Capture Driver, as shown in Figure 12.4.

Figure 12.4. Select the Camtasia driver from the Flash player's Camera Settings panel.

graphics/12fig04.gif

Camtasia is available on the Internet from the Camtasia web site (http://www.Camtasia.com/).

Microphone Object

The Microphone object controls access to the microphone input on the client computer. Like the Camera object, the Microphone object controls such capture settings as sample and gain. You can set the Microphone object to also trigger events when it detects sound or silence. The Flash Communication Server is required to record or transmit the microphone source to other Flash clients; however, the Microphone object can be accessed locally without the server.

The Microphone object operates very similar to the Camera object. In fact, it is identical. To attach your microphone to output to the Flash player, add the following code to your Flash document:

my_mic = Microphone.get(); 
_root.attachAudio(my_mic);

The Flash player cannot access any other audio input port that may exist on your audio card, such as the CD or Line In. You are also restricted from distributing local documents, such as MP3, WAV, or AIF files, to the NetStream encoder. This said, you can always cross your inputs within your operating system.

The Microphone object, like the Camera object, has two events: onActivity and onStatus. They operate exactly the same way as the Camera's, except they sense sound instead of motion.

The onStatus event is triggered when the user allows or denys access to the microphone, and you can overwrite the onStatus function the same way you did with the Camera object. Two Information objects can be returned: Microphone.muted and Microphone.unmuted.

You have already seen how to connect your microphone to the publish stream in Exercise 7.4 in Chapter 7. It is as simple as attaching the Microphone feed to the NetStream object.

For a full list of the Microphone objects, refer to Appendix B.For some tips on troubleshooting your microphone, refer to the section on cameras and microphones near the end of this chapter.

NetConnection Object

The NetConnection object maintains a persistent two-way connection between the Flash player and the Flash Communication Server. NetConnection is the cornerstone of any communication application. The SharedObject and NetStream objects use a NetConnection object to exchange streams and ActionScript objects with the server. The NetConnection object can handle the transport of multiple SharedObjects and multiple one-way streams. It also handles broadcast messages within the streams and the SharedObjects.

Communication between client and server is achieved using the Real Time Messaging protocol (RTMP) built by Macromedia specifically for Flash Communication applications. RTMP is a binary format, but it cannot be encrypted. To establish a connection between the client and the Communication Server, use the connect method once the NetConnection object has been instantiated to a local variable:

nc = new NetConnection(); 
nc.connect("rtmp:/myApplication/myInstance", "my name", "my Pasword");

Note

The single forward slash, /, in the RTMP connection string is the correct way to reference a Flash Communication Server, if it is on your local computer. If you are accessing a remote server, use a double forward slash, //, as in:

rtmp://[servername]/[application]/[instance] 

The connect method invokes the application.onConnect method on the server. As you saw in Chapter 11, "Server-Side ActionScript (SSAS)," the onConnect method can accept any number of parameters you need. In the previous code sample, parameters for username and password were sent with the server string.

Uniform Resource Identifier (URI)

The Flash player establishes a RTMP connection by referencing the server with a Uniform Resource Identifier (URI). The URI can be an absolute value or a relative value.

An absolute URI looks like this:

rtmp://www.myServer.com/myApp/myInstance 

The absolute URI should be used if the Flash Communication Server uses a different URI than the calling SWF movie, which is usually the case if your SWF movie is on a different server than the Flash Communication Server. This is true for both development and production server setups. The downside to using an absolute URI is that the ActionScript would not be portable without modification to install on another server, such as your production server. Absolute URI's use a double forward slash, //, following rtmp:.

A relative URI uses only a single slash before rtmp: and looks like this:

rtmp:/myApp/myInstance 

The relative URI can be used if your Flash Communication Server occupies the same URI as the calling SWF movie, which is usually the case if your SWF movie and Flash Communication Server reside on the same machine. Most development environments are set up with the SWF and Communication Server sharing a single machine. Adopting this method will ensure your code stays as portable as possible, so that when your application is complete you don't need to change any code to deploy it to your production server.

NetConnection onStatus Event

Like the Camera and Microphone objects, NetConnection also has an onStatus event. This event is often used to ensure a connection is present before starting operations on it, as in:

nc.onStatus = function(infoObj){ 
trace("level: " + infoObj.level + "code: " + infoObj.code);
}

The NetConnection status handler can receive a large number of Information objects, but only three code values are critical for most communication applications:

  • NetConnection.Connect.Success Sent by the SSAS function application.acceptConnection(). When this value is received, the connection has been accepted by the server and can start handling SharedObjects and NetStreams. Test for this code value first, and then start connecting the required resources only after receiving it.

  • NetConnection.Connect.Rejected Received when the SSAS function application.rejectConnection is called. Usually this function is called when the client has passed incorrect credentials to nc.connect.

  • NetConnection.Connect.Closed Received when the network connection has failed or the server is unreachable. You should monitor this code closely and take action informing the user that there is a problem with the connection to the server. The code also will be sent when the server calls the application.disconnect() method.

There is a generic onStatus "catch-all" script template in Appendix E,"Useful ActionScript Templates Quick Reference." You can use this script to handle all NetConnection Status changes. The script is also available through the book's web site (http://flashcom.PangaeaNewMedia.ca/).

Calling Remote Functions Over NetConnection

Custom NetConnection methods add routines to the NetConnection object prototype or instance. Adding methods to the object exposes them to the server. This means that the server (SSAS) can call functions or properties that you set in Flash. This is a great technique with a million uses. For example, you could use NetConnection methods to enable a client's web camera or control the Timeline play head on a client. This technique could also be used for instant notification or messaging.

Creating a function within the NetConnection object is simple. Here is an example:

nc.turnOnCamera = function("message"){ 
      trace("The Server Says: " + message);
      my_video.attachCamera(Camera.get());
return("Camera has been enabled!");
}

The server calls this function like this:

application.onConnect = function(clientObject){ 
application.acceptConnection(clientObject);
clientObject.call("turnOnCamera", new clientRet(),"I Can See You");
/* This function will be closed in the next step */

Similar to the SSAS Client object, the function executes remotely. The server may not have the results fast enough to process them immediately, so the results are sent to a client results object called clientRet. This return function can contain two events: onResult and onStatus. This script listing will follow the Client object call made earlier:

      clientRet= function() { 
            this.onResult(value_ret) = function() {
            trace("The Client Says:" + value_ret)
            }
      }
/* Close the application.onConnect() Function earlier */
}

When the client has completed the request, it returns a result object to the server. The onResult method will be invoked within the clientRet object.

Because the NetConnection is a two-way exchange, functions defined within the object are the only client-side functions that can return ActionScript objects to the server. SharedObject and NetStream functions are only one-way and cannot return a result to the caller server.

ActionScript objects transferred over the NetConnection are exchanged using the Action Message Format (AMF) over RTMP. Handled by the server and the Flash player, this format is completely transparent to the developer. AMF is also used transparently with Flash Remoting MX in the NetServices object.

For a full list of the NetConnection objects, refer to NetConnection in Appendix B.For a detailed listing of all NetConnection Information objects, refer to Appendix C,"Information Objects (Server and Client) Quick Reference."

NetServices Object (Flash Remoting MX)

The NetServices object is used to transfer ActionScript objects with Flash Remoting MX services using AMF over traditional web HTTP or HTTPS. The object is primarily used to call methods on remote services, such as an application server connected to a database, or other servers, such as a mail or LDAP server. A NetServices connection is nonpersistent, meaning that it only connects when a service is called or returned. This is very different from the sustained connection achieved by the RTMP protocol and the NetConnection object.

NetServices (or Flash Remoting MX) is available for both the Flash Communication Server and the Flash client. The server-side and client-side NetService objects are identical and perform the same operations. In Flash MX, you are required to manually load the NetServices Libraries before you can use them.

To load (or include) the NetServices Libraries in Flash MX, place these lines at the beginning of your ActionScript:

#include "NetServices" 
#include "NetDebug" // used to engage the NetConnection Debugger

There are only three NetServices methods:

  • SetDefaultGatewayURL

  • createGatwayConnection

  • getServices

These methods are responsible for defining the connection location and the service to connect to. The listing below references a remote service called myFolder.myService on the server www.myRemotingServer.com:

NetServices.setDefaultGatewayUrl("http://www.myRemotingServer.com/flashservices/gateway");
graphics/ccc.gif 
gatewayConnnection = NetServices.createGatewayConnection();
myServiceRef = gatewayConnnection.getService("myFolder.myService", this);

The Flash Remoting MX service is instantiated in the variable myServiceRef. Flash now has access to any method (service function) defined within the service. In Chapter 14, "Server Administration," you will learn the details of Flash Remoting MX to create and serve service functions to the Flash Communication Server and Flash Player 6.

This process calls the Flash Remoting MX service functions from Flash Player 6. If you are using the SSAS NetServices, none of this is required. The Flash Communication Server can be used as a mediator to distribute content returned by Flash Remoting MX providers.

For full details of the NetServices (Flash Remoting MX) objects, refer to Appendix B.Also refer to Chapter 13, "Accessing External Data," for examples and details.

NetStream Object

The NetStream object is a one-way streaming connection between the Flash player and the Flash Communication Server. The NetStream object is used to transmit or receive video and audio, and to broadcast messages between the Flash player and the Flash Communication Server.

The Flash player can attach an audio or video stream to Flash MovieClips or embedded Video objects, just as it directly connects the camera and microphone sources.

You can open as many one-way NetStreams as your application requires. The following script can be used to connect two NetStreams to the same NetConnection (nc):

publish_ns = new NetStream(nc); 
subscribe_ns = new NetStream(nc);

This listing does not determine which way the streams are going. It simply instantiates the object to local variables. Each instance of the NetStream object shares the NetConnection object to communicate with the server. The total bandwidth available is divided between each stream equally.

Publishing a Stream

Publishing (on the Client) is the process of sending a one-way stream originating from the Flash player to the server. The stream will send any valid camera or microphone source or ActionScript object of any type. The Flash player can publish to a Flash Communication Server only. It cannot publish directly to another Flash player. The SSAS object Stream can publish a prerecorded stream or be used to redirect client streams. This process is examined in Chapter 18, "Build Training and Education: The Virtual Classroom." The following code demonstrates how to use the Flash player to send (publish) a camera and microphone stream to the Flash Communication Server:

// attach the Microphone and Camera to the publish_ns stream 
publish_ns.attachAudio(Microphone.get());
publish_ns.attachVideo(Camera.get());

At this point, the stream has still not been identified to the server. The publish method establishes the connection and determines it will be traveling to the server with the name myStream.

// start publishing the combined camera and microphone feed 
publish_ns.publish("myStream", "record");

The second parameter informs the server what to do with the stream in terms of recording. There are three options available:

  • record Saves the live stream to the server as a FLV file.

  • append Adds the live stream to the end of an existing FLV file.

  • live The default setting, and the server will not handle the incoming stream.

The example code engages the recorder and starts saving the stream to a file called myStream.flv in the application's stream folder.

If you review the App Inspector, you will see an entry in the Streams tab showing your stream being published. You will also see clients who are subscribing to it.

At this point, permissions assumed, any client connected to the application instance can subscribe to the stream called myStream. The next section will create a real loopback that will subscribe to the same stream it is publishing. This effect could be achieved using the Camera.loopback() function. For this example, however, the stream will actually take a round trip from player to server and back to the player.

Subscribing to a Stream

Subscribing is the process of receiving a one-way stream originating from the server or from another client connected to the server. A subscribed stream can receive any media source or ActionScript object of any type.

The following script will attach any media being sent on the subscribe_ns stream to an embedded video object on the Flash stage with the name my_video:

my_video.attachVideo(subscibe_ns); 

At this point, the stream has been associated, but has not been established with the server. Its direction has not yet been declared. To establish the connection and identify the connection as a subscription, the play() method is called. To connect to a live or recorded stream with the name myStream, use the following code:

ns.play("myStream", -2, -1, false); 
// Start the stream, "myStream",
// (-2) if the live source is not available,
// look for a recorded stream of the same name.
// (-1)Play until the stream is over

The play method has a series of parameters that control the starting position (for nonlive streams) and the length of play, as well as a Boolean value that will clear a play list (more on that shortly). For full details on the parameters of the play method, refer to Appendix B.

At this point, the Flash player will start receiving the stream. If you review the App Inspector, you will see an entry in the Streams tab showing your subscription stream. You will also see clients who are subscribing to it.

The subscribed stream will begin to play once the NetStream buffer has been filled with enough stream to start playing. The buffer is a memory allocation that will temporarily store incoming stream data before it is played back. This is done to ensure you do not experience drop outs due to network congestion. Think of a portable CD player with an anti-skip feature. This allocates a bit of memory that will preload your CD music before you start hearing it. If the CD skips, it will start playing from memory. The buffer is the same idea, except instead of avoiding skips, it avoids network congestion.

The default buffer size is 2 seconds. You can change this using the setBufferTime() method.

NetStream PlayLists

Play lists on the client operate exactly the same as PlayLists on the server. You can stack play commands to create a sequence of video using multiple stream sources. You can also use multiple play commands to jump back and forth on a single prerecorded Flash video, in essence creating a dynamic edit decision list (EDL). You could even create a solution that will give your user the ability to edit and play back the sequence without touching the original source.

You can force a play command to override a play list by setting the last parameter to true. This will flush the play list.

NetStream Messaging

Earlier in this chapter, you learned that you can send ActionScript objects across the NetStream object. This is similar to calling a method over the NetConnection object; however, the principle difference is that NetStream is one-way. Methods invoked over this object cannot return anything to the caller. Messaging over NetStream is called broadcasting a message. It is achieved by invoking a method defined within the NetStream object on the client using the NetStream.send() method.

Consider this example: During a video broadcast, the user publishing the stream wants to illustrate a point by having each subscriber go to a specific web page. What if the publisher could send the URI of the web page through the stream and automatically open a web browser and have each computer that is subscribed go to that web page? That is a perfect example of what you can do with NetStream messaging.

On each client would be a function defined in the subscription NetStream object. This function would receive one parameter, the URI, and pass it to the getURL() function, similar to:

subscribe_ns.openBrowser = function(URI){ 
getURL(URI,"_blank");
}

The Flash stage of the publisher has a text input box with the instance name URItoSend_txt on the stage to allow the entry of any web site URI. When the user clicks a PushButton, it invokes a Click Handler that will call the method, openBrowser, passing the URI to each client subscribed to the stream. Here's the example code:

// Assign a the Click Handler to the PushButton, "submit_pb" 
submit_pb.setClickHandler("broadcastURI");

// The Function invoked when the pushButton is clicked.
broadcastURI = function () {
      publish_ns.send("openBrowser", URItoSend_txt.text);
};

The .send() function calls a method on each subscriber named openBrowser and passes it the value of the text input field. As you saw earlier, this method will invoke the getURL() method on each client and open the link in a new web browser.

NetStream onStatus Event

The NetStream object also has an onStatus event that will be sent a notification each time the status of the stream (publish or subscribe) changes. There are a lot of Information objects associated with NetStream. They are broken down in to errors, warning, and noncritical status updates relaying information about the buffer, subscription (Play), publish, recoding, and seeking. A full listing of every NetStream Information object is available in Appendix C.

For full details of the NetStream object, refer to Appendix B.You should also review the SSAS Stream object in Appendix A,"Server-Side Objects Quick Reference." Appendix E contains some quick reference scripts that you can use to quickly create publishing and subscription streams with ActionScript.

RecordSet Object (Flash Remoting MX)

The RecordSet object is a sophisticated array of ActionScript objects that operates as a standard database query result set. The principle origin of the RecordSet object was to allow a Flash Remoting MX server to convert a standard Query Result Set into something that the Flash player could understand. This is where AMF comes into the picture. Flash Remoting MX allows application servers to respond to remote method requests and return their unique data objects to the Flash Remoting MX interpreter (AMF). AMF converts the data objects into normal ActionScript variable types. In the case of a Query Result Set, Flash traditionally had no object that could handle database columns and rows natively.

Macromedia introduced the RecordSet object with Flash Remoting MX to allow AMF to format a Query Result Set into something Flash could understand. The RecordSet is a complex associative array, with a series of query-like methods and properties. These objects allow ActionScript to interact with the RecordSet with traditional query-like methods, such as getColumnNames and referencing data by row number and column name.

RecordSet can be used with or without Flash Remoting MX. The object itself is a series of methods and properties with a prebuilt data management model. When the object's class is included, RecordSet becomes a standard ActionScript object that can be sent to a method or can occupy a slot on a SharedObject. The server-side and client-side RecordSet objects are identical. On both platforms, you must manually load the RecordSet Libraries to begin using them.

To load the RecordSet Libraries in Flash MX, add the following line at the beginning of your ActionScript:

#include "NetServices.as" 

This Flash ActionScript file adds the NetServices and the RecordSet classes to your Flash movie.

The script in Listing 12.1 demonstrates how you can use the RecordSet object and its methods to quickly populate a RecordSet without using Flash Remoting MX. Normally, a RecordSet object is created by a service method returning a database result from the application server. For those of you familiar with handling databases, this is a great technique to work with structured data in a way that you might be familiar with.

Listing 12.1 Sample Usage of the RecordSet Object
my_rs = new RecordSet(["fname", "lname", "email", "userName", "Password"]);

// INSERT some data (3 rows) to the RecordSet
my_rs.addItem({fname:"Kevin", lname:"Towes", email:"ktowes@pnm.ca", userName:"ktowes", 
graphics/ccc.gifPassword:"tin"});
my_rs.addItem({fname:"Kary", lname:"Livsey", email:"karyh@skiForLife.com", userName:
graphics/ccc.gif"kary", Password:"river"});
my_rs.addItem({fname:"Scott", lname:"Hepworth", email:"scotty@paddleMyBoat.com", userName:
graphics/ccc.gif"scott", Password:"fox"});

// ** UPDATE (replace) a column value in record 1
my_rs.setField(1, lname, "Hepworth");

// ** SORT The Data by last Name
my_rs.sortItemsBy(lname,"desc");

// OUTPUT some fields:
trace("your name is: "+my_rs.getItemAt(2).fname);

Compare the addItem() method to a SQL Insert command used to add data into a database. In ActionScript the syntax is:

my_rs.addItem({fname:"Kevin", lname:"Towes", email:"ktowes@pnm.ca", userName:"ktowes", 
graphics/ccc.gifPassword:"tin"}); 

The SQL Insert syntax is:

Insert into my_table (fname,lname,email,username,password) 
VALUES('Kevin', 'Towes', 'ktowes@pnm.ca', 'ktowes','tin');

As you can see, the same amount of code is required. Now, compare the update methods. In ActionScript, this is achieved with the setField() method:

my_rs.setField(1, lname, "Hepworth"); 

In SQL, the UPDATE command is used:

UPDATE my_table SET lname = 'Hepworth' WHERE ID=1; 

For full details of the RecordSet object, refer to RecordSet in Appendix B.Also refer to Chapter 14 for detailed examples and interacting with a database.

SharedObject

The SharedObject is a programming model to share data between Flash players and servers in a persistent or temporary fashion. The SharedObject, in concept, is identical to the SSAS SharedObject, except in its implementation. For a real understanding of the SharedObject, refer to Chapter 11, "Server-Side ActionScript," and Chapter 8, "STEP 8: Collaboration with SharedObject()."

Let's start by detailing the different implementations of SharedObjects in Flash versus the Flash Communication Server. There are two major differences between the two. Flash ActionScript has two flavors of SharedObject: the Local and the Remote.

Local SharedObject

The local SharedObject is similar to an HTML cookie. It is a file that is saved to the client's hard disk. It is persistent when the user closes the Flash movie, and can be accessed when the Flash movie is reopened. The local SharedObject is useful for storing specific values that may affect the Flash movie, such as the frame number the player was displaying before shutdown. When a user opens the Flash movie, the state of the Flash movie would be maintained. This could also be used to transfer data from a Remote SharedObject, so that if the Flash movie became disconnected from the server, the user could sustain some operations, such as interacting with an address book.

Like the SSAS implementation of SharedObject, the local SharedObject writes its SO data to the hard disk on two occasions: when the movie is shut down and when the Flush command is invoked. Here is a simple implementation of the local SharedObject.

lcl_so.getLocal("myLocalSharedObject"); 

// Write a property to the Local SharedObject
lcl_so.test = " kevin";

// Read a property from a Local SharedObject
var my_var = lcl_so.test;

// Trace the data
trace(" Local SharedObject Read Test: "+my_var);
trace("LocalSize: "+lcl_so.getSize());

Local SharedObjects do not require the Flash Communication Server to operate, as the Remote SharedObject does.

Remote SharedObject

The remote SharedObject is similar to the local SharedObject. It is not stored on the local computer, however, and must be used with the Flash Communication Server. The key operational difference is the synchronization that occurs between each connected client and the server. The synchronization process is identical to the SSAS implementation. You can review the synchronization processes in Chapter 11. There is also a great onSync ActionScript template in Appendix E.

Let's review the differences in implementing SharedObjects on the Flash client and within SSAS. Table 12.1 demonstrates the ActionScript and feature differences.

Table 12.1. Differences Between the Client- and Server-Side Implementations of SharedObject.

Command

Flash ActionScript

Server-Side ActionScript

Calling the SharedObject

so =
SharedObject.getRemote();
so.connect();
so = SharedObject.get()

Writing a data property (SLOT)

so.data.mySlot = 
value; or so.data
[mySlot] = value
so.setProperty
("mySlot","value");

Reading a data property

my_var = so.data.mySlot;
or my_var = so.data
(mySlot);
my_var = getProperty
["mySlot"]

Synchronization

Same implementation

Same implementation

Status Information Objects

Same messages

Same Messages

Monitoring changes

A frequency value set

;
using so.setFPS()

Changes are instantaneous

Locking

No (only with local SharedObjects)

Yes

Sending/receiving broadcast messages

Yes: so.Send(); (same implementation)

Yes: so.Send(); (same implementation)

Flushing

No (only with local SharedObjects)

Yes

Clearing and purging

No

Yes

Retrieve size

Yes

Yes

Proxy SharedObjects

No

Yes

As you can see, the Server has more control over the SharedObject. This is because the actual object exists within the local resources of the server. The location offers additional functionality to the server.

For full details of the SharedObject implementations on the Client, refer to Appendix B.Also refer to Chapter 8, "STEP 8: Collaboration with SharedObject ()," for detailed examples.

System Object

The System object is used to return information about the Flash player environment. There two principle methods that can be used with the object: capabilities(), which returns the resources available to the Flash player, and showSettings(), which invokes the Flash player's Security Settings panel.

System Capabilities

This object was available in the release of Flash MX and is documented in the product manual and the online dictionaries. You should be aware of this method and its properties when developing Flash Communication Server applications. Invoking the capabilities function is like accessing raw data. The returned data must be parsed by you. The string below is a sample of the capabilities return variable:

"A=t&MP3=f&AE=gsm&VE=h11&ACC=f&V=WIN%206%2C0%2C0%2C129&M=Macromedia%WINDOWS&R=400x 
graphics/ccc.gif200&DP=72&COL=color&AR=1.0&OS=WINDOWS%2000&L=en-US" 

As you can see, it's a URL-encoded name and value pair string. An easier way to interact with this data is using the System.capabilities properties. For example, to return if the player has MP3 abilities, you could simply use the following string:

System.capabilities.hasMP3; 

This property will return a Boolean value. You may be asking, "Aren't all Flash players the same?" No, they are not. Flash players have different support features and are even coded differently for each device, browser, and operating system. Flash Player 6 on a mobile device has different properties than the player installed on a PC running in Netscape. The most obvious difference is the screen size and dots per inch. Using the System object you can dynamically control what is delivered to the device, based on the capabilities method.

For full details of the System object capabilities, refer to Appendix B.

System Settings Panel

The System object contains another method that was not documented in the manuals or the online dictionaries. The method System.showSettings() lets you control the Flash player's Settings panel. The Settings panel lets the user customize settings to local resources, such as access to the camera, microphone, or hard disk and the devices the Flash player uses for microphone and camera input. Figure 12.5 displays the four panels available.

Figure 12.5. The Settings panel contains four screens.

graphics/12fig05.gif

You can use the System.showSettings(whichPanel) method to force a panel to appear. A common use of this is when the user denies access to the microphone or camera and your application requires these devices to operate. You can message the user, informing him of the requirement, and force the Settings panel to reappear. Each panel is associated with a number (0?3). 0 references the first tab, and 3 references the last tab (camera). If you do not supply which panel to open, the panel that was displayed last will appear.

The Settings panel can also be accessed by the user right-clicking (Cmd-click on the Mac) anywhere in the Flash player.

Video Object

The Video object is a placeholder on the Flash stage that handles video sources from imported or linked video assets, the Camera object, and NetStream. This is a critical element to decompress and display incoming streams from the Flash Communication Server. The Video object can't really do much on its own. Its key feature is the control it has over the internal (Sorenson Spark) decompressor (codec). Most of the operations on actual playback are handled by the NetStream object. If you are using the Video object to handle imported video (without Flash Communication Server), then simple Timeline commands are used to control the playback.

For full details of the Video object's compressor controls and monitoring properties, refer to Appendix B.Also refer to Chapter 7 for detailed examples about using the Video object with NetStream.



    Part I: 10 Quick Steps for Getting Started
     
    ASPTreeView.com
     
    Evaluation has µјКЪТєЛНШexpired.
    Info...