Menu:

Sponsor

Discover Master of Alchemy, our first iPad/iPhone and iPod touch game!

Follow Me

 

Forum's topics

Latest Files

Archives

Top Rated

Categories

Photo Gallery


Flash Media Server and AMFPHP

4. Flash Media server application

Open your flash comm installation folder, usually C:\Program Files\Macromedia\Flash Media Server\applications.
Create a folder "sample_remoting" and inside this folder create a new file "main.asc".
The main.asc file is the base file which flash comm runs by default when an application starts.


/**
 * flash comm server & flash remoting example
 * How to use a simple flash comm server with
 * a remoting application inside
 */

// load the remoting classes
load("netservices.asc");


// on application started
application.onAppStart = function(){
    trace(' -------------------------------- ');
    trace('application started: ' + this.name);
    trace(' -------------------------------- ');
    // set the default gateway URL
    NetServices.setDefaultGatewayUrl("http://localhost:8080/flashservices/gateway.php");
    this.gatewayconn = NetServices.createGatewayConnection();
}

// once a new client connects
application.onConnect = function( clientObj ){
    clientObj.validuser = false;
    // set in the client object the remoting services informations
    // and assign a default handler for the remoting calls (AMFPHPResult)
    clientObj.serv = this.gatewayconn.getService("flashcommtest", new AMFPHPResult( clientObj ) );
    // function called from an swf client
    clientObj.validateUser = function( username, password ){
        this.serv.isValidUser( username, password );
    }
    // function called from an swf client
    clientObj.registerUser = function( username, password ) {
        this.serv.addUser( username, password );
    }
    // accept the client connection
    this.acceptConnection( clientObj );
}



/**
 * Remoting Object
 * Default responder object for remoting calls
 */

function AMFPHPResult( client ) {
    // set the client object
    this.client = client;
}

AMFPHPResult.prototype.isValidUser_Result = function( data ){
    this.client.validuser = data;
    // send back the results to the client object
    // by calling a method inside the netconnection object
    this.client.call("isValidUser_Result", null, data);
}

AMFPHPResult.prototype.addUser_Result = function( data ){    
    this.client.validuser = data;
    // send back the results to the client object
    // by calling a method inside the netconnection object    
    this.client.call("addUser_Result", null, data);
}

 

We can divide the script into 3 parts:

  1. first load the netservices.asc class file.
    This is similar to what we used to do in Flash to use Remoting, #include "NetServices.as" file. FlashComm has not updated to AS2 so we still use the old NetServices class which is very similar to Flash Remoting. Inside a flash comm application we need to load that class using the "load" function, instead of the compiler directive #include.
  2. create the application structure by overwriting 2 application methods: onAppStart and onConnect.
    Application
    object contains information about a Flash Communication Server application instance that lasts until the application instance is unloaded.

    onAppStart is invoked when the server first loads the application instance. In this event we just define the gateway connection to the remoting service and store it as variable into the application object ( this.gatewayconn).

    onConnect is invoked on the server side when NetConnection.connect is called from the client side and a client attempts to connect to an application instance. The parameter passed "clientObj" refers to the flash client which attempts the connection.
    In this case what to do is define into every client object a variable "serv" which is the reference to the flash remoting service class "flashcommtest", and assign for the remoting calls a new object "AMFPHPResult" object which will be the default result handler for every amfphp call.

    Finally define for every client the methods which it can call: validateUser and registerUser. These methods will be called from a flash client using netconnection.call method (we will see later ).

    Last thing to do when overriding onConnect method is to use Application.acceptConnection(clientObj ) in order to allow the client to connect to the server. (if you don't want the client to be accepted, use Application.rejectConnection( clientObj ).
  3. Define the default result handler "AMFPHPResult" which will receive all the amfphp results and will call methods into a flash client (using client.call method).

    the method client.call executes a method on the originating Flash client. The remote method may optionally return data, which is returned as a result to the resultObj parameter, if it is provided. The remote object is typically a Flash client connected to the server, but it can also be another server. Whether the remote agent is a Flash client or another server, the method is called on the remote agent's NetConnection object.

You can find more documentation about Flash Comm Server scripting and management here: http://livedocs.macromedia.com/flashcom/mx2004/index.html

 

5. The Flash Client

Now it's time to create the Flash Client app and put all together.

Remember to start your webserver and your flash comm server and maybe go into the admin console, if you want to debug your application ( in the .asc file you can use trace function too).

The fla first frame contains all the base functions for managing the netconnection object:


// redirect user to the chat frame

// handler for the mx.controls.Alert class
function gotoChat(evt){
    trace('gotoChat');
    _root.gotoAndStop('logged');
}

// redirect user to registration frame
// handler for the mx.controls.Alert class
function userChoice(evt){
    trace('userChoice')
    if(evt.detail == 1){
        _root.gotoAndStop('register');
    }
}

// ***********************************
// respond to a remote status messagge
function nc_Status(info:Object):Void{
    switch(info.code){
        case 'NetConnection.Connect.Failed':
        case 'NetConnection.Connect.Rejected':
            // connection failed
            mx.controls.Alert.show(info.code, "Status", _root, null, "", mx.controls.Alert.OK);
            break
        case 'NetConnection.Connect.Success':
            // connected
            _root.gotoAndStop('intro');
            break;
    }
}

// create the netconnection object
var nc:NetConnection = new NetConnection()
// assign the hander for the onStatus messages
nc.onStatus = nc_Status
// handler for remoting calls
nc.isValidUser_Result = function( data ){
    if( data == true ){
        mx.controls.Alert.show("Valid user!", "Success", mx.controls.Alert.OK, _root, gotoChat);
    } else {
        var msg:mx.controls.Alert = mx.controls.Alert.show("Not a valid user, do you want to register a new user?", "Error", mx.controls.Alert.YES | mx.controls.Alert.NO, _root, userChoice);
        msg.setStyle("themeColor","haloOrange");
    }
}
nc.addUser_Result = function( data ){
    if( data == true ){
        mx.controls.Alert.show("Registration success!", "Success", mx.controls.Alert.OK, _root, gotoChat);
    } else {
        var msg:mx.controls.Alert = mx.controls.Alert.show("There were problems registering the new user, please try with a different username", "Error", mx.controls.Alert.OK, _root, null);
        msg.setStyle("themeColor","haloOrange");
    }
}
// finally connect to flash comm
nc.connect("rtmp:/sample_remoting");
// **************************************
stop();

 

As you can see the nc object is the main object which controls the communication with the flash comm server.
first define the connection object with nc = new NetConnection().
Then assign an handler for the onStatus method, for us is nc_Status which will receive as parameter an object "info" with all the information about the connection with the server

NetConnection.onStatus: Event handler; invoked when a status change or error is posted for the NetConnection object. If you want to respond to this event handler, you must create a function to process the information object sent by the server.

Inside the nc object we will define 2 methods: isValidUser_Result and addUser_Result which will be called from the main.asc file once a remoting result arrives, and exactly from these lines of the "main.asc" file:

  • this.client.call("isValidUser_Result", null, data);
  • this.client.call("addUser_Result", null, data);

These methods need to be defined into the netconnection object in order to work!

Finally connect to the server using:
nc.connect("rtmp:/sample_remoting");

NetConnection.connect:

protocol:[//host][:port]/appname/[instanceName]

For protocol, specify either rtmp or rtmpt. If rtmp is specified, Flash Player will create a persistent socket connection with Flash Communication Server. If rtmpt is specified, Flash Player will create an HTTP "tunneling" connection to the server. For more information on RTMP and RTMPT, see the description section below.
You can omit the host parameter if the Flash movie is served from the same host where Flash Communication Server is installed.
If the instanceName parameter is omitted, Flash Player connects to the application's default instance (_definst_).
By default, RTMP connections use port 1935, and RTMPT connections use port 80.

 

Figure 1

This is the screenshot of the login frame. The login button has this script:

on (click) {
    this._parent.nc.call("validateUser",null,this._parent.userName.text, utils.string.md5(this._parent.userPassword.text) );
  } 

This means this will make a call into the nc object in order to call a remote method, defined in the main.asc file. This method has been defined into the onConnect event of the main.asc file and created into the clientObj object. All the methods defined into the clientObj object can be invoked using this syntax (NetConnection.call)

These are the steps:

  1. netconnection object invokes the validateUser method into the main.asc file.
  2. the validateUser remote function will call the isValidUser method of the AMFPHP class file, which will make a query to the MySQL table to check if user is valid.
  3. Then the result arrives into the AMFPHPResult.prototype.isValidUser_Result handler
  4. AMFPHPResult finally invokes the nc.isValidUser_Result

 

 

 

Figure 2

Registration screenshot.
In this frame the "register" button makes this call:

this._parent.nc.call("registerUser", null , this._parent.userName.text, utils.string.md5(this._parent.userPassword.text) );

This invoke the clientObj.registerUser into the main.asc file, which will invoke the amfphp method "addUser" adding a new record into the MySQL table. Once a result arrives to the AMFPHPResult handler, nc.addUser_Result will be invoked into the flash client.

 

 

For a complete and more detailed overview of the swf application, download the tutorial zip file and open the fla contained in it.

 

6. Files download

Download files used in this tutorial