'NetConnection()' Methods, Properties, and Events

If you are not familiar with programming, it is important to understand that every object has three components. Object methods (or behaviors) are internal functions that affect the property (or characteristic) of an object. For example, in a movieClip, the method .gotoAndPlay() affects the MovieClip property _currentFrame. Properties (or characteristics) are variables that contain values describing an object. For example, a MovieClip on the Flash stage has _x and _y properties. The values of _x and _y are numbers representing the x and y position of the MovieClip. Most properties can read or be written to. For example, a MovieClip can be repositioned by changing the value of the _x and _y properties. Some properties are read-only, such as the _currentFrame property.

Events act as listeners that respond to actions or inputs affecting the object. For example, when you move your mouse over a button, you trigger an onMouseOver event. Events must be overwritten. That means no default (prototype) actions are associated with an event. You are responsible for creating event actions by overwriting the default event handler. Consider the onMouseOver event. You can script a sound effect to play when the user rolls over the button triggering the onMouseOver event. The NetConnection() methods are as follows:

  • .connect() Establishes the connection between client and server. On the server, this method is handled by the Application.onConnect() event.

  • .close() Disconnects the connection between client and server. On the server, this method is handled by the Application.onDisconnect() event.

  • .call() Invokes a server method defined within the application. Methods are defined with the main.asc file.

The NetConnection properties are as follows:

  • .IsConnected Returns a true or false. It is affected by the connect()and close() methods.

  • .uri Returns the Uniform Resource Indicator connection string used in the connection. This is used to easily access the correctly formatted value.

The NetConnection event is onStatus. This event is called to handle server status changes. Status changes include errors, connects, and disconnects.

Full details of the NetConnection object are listed in Appendix A,"Server-Side Objects Quick Reference."

Why would you even bother using ActionScript to connect, when there is a simple UI component (SimpleConnect) that will do it all for you? The answer is simple: control. Using ActionScript to manage your communication with the server allows you to leverage the server in ways that are just not possible with the SimpleConnect component.

Controlling the data flow, sending messages, accessing a database, streaming video, or controlling a live broadcast or networked video game cannot be done without the use of ActionScript. Exercise 6.1 will introduce you to using ActionScript to connect with the Flash Communication Server.

Exercise 6.1: Get Connected with ActionScript and NetConnection()

This exercise establishes a connection using ActionScript using the Communication UI components without SimpleConnect. Before coding, there are two things you need to do. First, set up a new application folder on the server; then create a new movie and add a couple UI components to your movie:

  1. Create the application folder on the server in the /flashcom/applications/folder. Call it mySecondApp.

  2. Copy the main.asc file from your previous example into the new mySecondApp folder. If you want to create a new main.asc file, make sure the following line of code is included:

    load("components.asc"); 
    
  3. In Flash MX, place a ConnectionLight and a PeopleList UI component on the Flash stage.

  4. Select the ConnectionLight and give it the instance name of connectionLight_mc in the Properties panel. This gives you some visual feedback when a successful connection has been established with the server. Give the PeopleList component the instance name of peopleList_mc.

Now you are ready to start coding.

Connecting Communication Server using ActionScript is pretty simple. Not quite as simple as the SimpleConnect UI component, but simple none the less. With the Flash ActionScript Editor open (F9) and set to Expert mode (Ctrl+Shift+E), follow these steps:

  1. Enable the NetConnection Debugger by including the NetDebug class files. Add the following line of code to Frame 1 on Layer 1:

    // Include the Debug Class file 
    #include "NetDebug.as"
    
  2. Create an instance of the NetConnection object. If you are new to coding, this procedure copies all the methods, properties, and events defined inside the NetConnection prototype. This instance (or copy) of NetConnection is called myConnection_nc. Notice the _nc suffix. This triggers the NetConnection code hints when it is typed into the editor. Add the following code on line 3:

    // create a new instance of the NetConnection object 
    myConnection_nc = new NetConnection();
    

    Tip

    If you do not see code hinting, the required library XML file was not installed properly. You must reinstall it.

    If Flash Communication Server is not running on your computer, you can use the installer to reinstall the authoring components.

    If Flash Communication Server is installed on your computer, you have to uninstall and reinstall the server, or run the installer on a computer that does not have Flash Communication Server installed and copy the following file.

    The file that Flash MX requires to populate the ActionScript panel is the communication.xml file. This file must be placed in the following folder:

    %Install Path%\Flash MX\First Run\ActionsPanel\CustomActions\
    
  3. Trace the status of the connection to monitor if the connection was successful or failed. Ultimately, you use this process to send a message to the user should the connection fail. The method onStatus is an event that is invoked to handle status messages sent from the server:

    // handle any status changes and responses from the server 
     myConnection_nc.onStatus = function(info) {
          trace("LEVEL: " + info.level + "   CODE: "+info.code);
    };
    

    This is called overwriting the onStatus function. This is done because the NetConnect.onStatus function wasn't programmed and doesn't do anything. When the server's status changes, the onStatus function runs to handle the response. It now traces any messages from the server to the output window when the movie is tested. By building some advanced handling, you can create a great way to inform the user that something has happened to the connection.

    The way it works is simple. The server returns its messages as an Information object, which is stored in a function variable. In our case that variable will be info. The object has two properties (CODE and LEVEL) that you can access and challenge. The Call.Failed code and the connect.Rejected code each return an additional property. Appendix C,"Information Objects (Server and Client) Quick Reference," contains a library of every Information object used by Flash Communication Server objects on the server and within Flash MX. As a helpful hint, a description of what you should do when you receive this error is available in Appendix C.

  4. Make the connection call to the server specifying the server name, port, application, instance, and username. The Connect method sends the first command to the server. The first parameter of this function is the location of the Communication Server:

    // Make the connection to the server 
    myConnection_nc.connect("rtmp:/mySecondApp/myInstance", "Kevin Towes");
    

    This script assumes you are running Flash Communication Server on your local computer. If your server is not on the localhost or on the same domain as your SWF file, add the reference to the server (//192.168.0.112) following the RTMP:/. You will also notice that you have to declare the name of the instance following mySecondApp. The SimpleConnect UI component you used earlier didn't require this parameter set in the RTMP string. Flash Communication Server automatically sets an instance called _definst_ if one isn't specified. In this scenario, you create your own instance called myInstance.

    Following the rtmp:/application/instance string, we are going to add a custom parameter to send a username. We handle this second parameter at the server by using it to log the user in to the application and accept the connection request.

  5. Connect the two UI components to the connection using their connect() methods. Each Communication UI component has set methods that control the component using ActionScript. For a full listing of UI component ActionScript commands, refer to Appendix D,"Flash UI Component Objects Quick Reference." Each component has a connect() method that assigns it to a particular connection. Add the following code to reference the peoplelist_mc and connectionLight_mc components to the myConnection_nc server connection:

    // Connect the UI Components to the new connection 
    peopleList_mc.connect(myConnection_nc);
    connectionLight_mc.connect(myConnection_nc);
    

That's it for the Flash ActionScript! You will have to develop some server-side ActionScript within the main.asc file to register the username with the UI component, but this example will run so you can test it. Save the file in either the application folder or a folder accessible by your second testing computer. Test the movie by selecting Control, Test Movie, or Ctrl+Enter.

If you have done everything correctly, you will see the connection light turn green. If it doesn't turn green, here are a few things to check:

  • Is the Flash Communication Server running? Test using the Administration Console or the App Inspector.

  • Is the application folder mySecondApp created within the applications folder?

  • Does the folder have the main.asc file in it with the command load("components.asc"); as the only command?

  • Is the ScriptLibPath mapped properly to the scriptLib folder? You can check this by opening the file: \\[serverInstallPath]\conf\_defaultRoot_\_defaultVHost_\Application.xml. Note, when you change this, you will need to restart the virtual host, or the server.

When your light is green, you will notice that your username doesn't appear in the PeopleList component. Don't worry; it won't display until you add some server-side script to handle the connection. So let's write the required server-side script to finish the job. Unlike Flash ActionScript, server-side ActionScript is case-sensitive (x != X). Now, step through the process of creating the ActionScript:

  1. Open the main.asc file in your favourite JavaScript editor or Dreamweaver MX.

  2. Overwrite the onConnect event. Application.onConnect will always be invoked when a Flash player requests a connection. Overwrite the .onConnect() function to perform two tasks just as you did with the onStatus() function inside Flash MX. Add the following code below the Load command in the main.asc file to start the function definition:

    application.onConnect =function(newClient,newUserName) 
    {
    

    Two parameters are sent from the player: the server string (newClient) and your name (newUserName). You can pass as many parameters as you need to the application.onConnect() method. A simple example might be to also handle a password variable. The server string is used to access a unique variable scope for the instance of the application. Each instance uses its own variable scope, which is important to maintain security of the instance. The property username will be set to the value of the newUserName variable.

  3. Accept the connection. The method acceptConnection() informs the player requesting the connection that the connection can be established:

    //Accept the connection from the user. 
    application.acceptConnection(newClient);
    

    This command does two things. First, it instantiates the Client object on the server (more on the Client object in Chapter 11, "Server-Side ActionScript") and second, it invokes the onStatus handler on the Flash player sending the Information object code value NetConnection.connect.success. You can use this method to create server-side authentication. Using a simple IF statement or even database matching, you can allow or deny connection requests. There is also a method called rejectConnection() that does not allow the client to connect. The Reject command also invokes Flash's onStatus handler sending the code Netconnection.connect.rejected.

  4. Register the name with the UI component. This command sets the username within the framework used by the Communication UI components:

    //Set the global user name for the UI Components 
    gFrameworkFC.getClientGlobals(newClient).username =newUserName;
    
  5. Trace the username to the Live Logs window of the App Inspector and close the function definition. Tracing in server-side ActionScript is the same as tracing in Flash MX. The output of server-side traces are displayed in the application's instance view on the Communication App Inspector:

          trace("Hi There, " + newUserName); 
    }
    
  6. Save the main.asc file.

Reload your application using the Communication App Inspector in Flash MX. Reloading the application is required because you made a change to the main.asc file. In Flash MX, load the App Inspector by selecting Window, Communication App Inspector. Log in using the proper host and login/password combination. Select the active instance mySecondApp/myInstance entry and click View Detail. With the Live Log tab selected, click Reload App. If you don't see this active instance, test your Flash movie again.

When Reload App is clicked, notice how the Live Log acts as the server-side ActionScript trace window.

Test your application again in Flash MX using Ctrl+Enter. Keep your eye on the App Inspector. The trace that was placed within the Application.onConnect is output to the App Inspector when you load your application. You should see the words "Hello There, Kevin Towes". If you put a different name in the connect string, you will see that.

The first connection is always the hardest. If you have a problem with the application, or are receiving errors in the App Inspector, the first thing to check is case sensitivity. Confirm each variable name and function against the example's ActionScript listing below.

Listing 6.1 Full Server-Side ActionScript Listing
application.onConnect =function(newClient,newUserName){
      //Accept the connection from the user.
      application.acceptConnection(newClient);
      //Set the global user name for the UI Components
      gFrameworkFC.getClientGlobals(newClient).username =newUserName;
      trace("Hi There, " + newUserName);
}

Exercise 6.2: Allow Multiple Users to Connect

Now that you can connect to the server, why not invite your friends to see what cool things you can do? Let's add a login prompt (similar to the SimpleConnect) so other people can connect and identify themselves. To accomplish this, all that is required is to wrap the connection string in Flash MX with a function. The function and connect calls are invoked when a login button is clicked. The hard-coded name also is changed to reference the value of a text input field. Exercise 6.2 steps you through the process.

First, save the document as a new name so you can keep the original. Save the FLA file as Step2-MultiConnect.fla in the same folder. Next, add some items to the Flash stage. You need the following:

  • One text prompt to ask the user to enter his name.

  • One input text field with the instance name login_txt.

  • One PushButton UI component as a login button with the label "login."

Set the Click Handler of the PushButton to appLogin. This function will be scripted shortly to establish a connection with the user's name. Your interface should look like Figure 6.5. Notice the Properties panel with the PushButton values.

Figure 6.5. Lay out your stage similar to this example. The Properties window is displayed because the PushButton is selected.

graphics/06fig05.gif

Now, let's rearrange the code you just wrote so the connection isn't made until a user enters her name and presses the Login button. To achieve this, the Connect method is wrapped in a new function called appLogin. This function is called when a user clicks the Login button (you specified this in the Click Handler property for the Login button). The hard-coded reference to the username in the connect string is made dynamic by referencing what the user enters into the input box "login_txt". Now, step through the process of creating the ActionScript:

  1. Open the ActionScript panel (F9) containing the code for this movie in Flash MX. If you cannot see the code, make sure you have selected Frame 1, Layer 1 in the Timeline.

  2. Place your cursor above the line connecting myConnection_mc to the server. Create a blank line in the code and enter the following line of code:

    appLogin = function() { 
    

    This is the start of the new appLogin function, but you have to close it now.

  3. Move your cursor to the end of the line containing the peopleList_mc.connect() string and press Enter to create a new line.

  4. Close the function with a closing curly bracket (}) in the line above the connectionLight_mc.connect string. The connectionLight.connect method is outside the function because it displays the current state of the connection, even before the connection has been established.

Your final code should look similar to what appears in Listing 6.2.

Listing 6.2 Final Flash ActionScript: Step2-MultiConnect.fla
// Include the Debug Class file
#include "NetDebug.as"

// create a new instance of the NetConnection object
myConnection_nc = new NetConnection();

// handle any status changes and responses from the server
myConnection_nc.onStatus = function(info) {
      trace("LEVEL: "+info.level+"  CODE: "+info.code);
};
// connect the application when the login button is pressed
appLogin = function () {
      // Make the connection to the server
      myConnection_nc.connect("rtmp://192.168.0.112/mySecondApp/myInstance", login_txt.
graphics/ccc.giftext);
      // Connect the UI Components to the new connection peopleList_mc.connect(
graphics/ccc.gifmyConnection_nc);
};
connectionLight_mc.connect(myConnection_nc);

Save the Flash movie and test it (Ctrl+Enter). You will notice the ConnectionLight is red. This illustrates no connection. Enter your name in the box and press Login. The light turns green when it connects, and you see the name you entered in the PeopleList component when the server accepts the user.

Locate the SWF file that was created in the same folder as the FLA file. Double-click it or drag it into a web browser leaving the player running in Flash MX. Log in, and you now see two names in the PeopleList box (see Figure 6.6).

Figure 6.6. The application is running within a browser. You can see there are two people logged in.

graphics/06fig06.gif

Tip

Always make sure you create the onStatus function before you connect. This ensures that you will see any status changes (errors and such) from the server as they happen. The best practice is to create nc.onStatus immediately following nc = new Netconnection.




    Part I: 10 Quick Steps for Getting Started
     
    ASPTreeView.com
     
    Evaluation has ЖЩНФЕexpired.
    Info...