Tutorials:Red5 and Flex 2 on Windows XP

From Red5Tutorials

Jump to: navigation, search

Tutorial for Red5 0.6.2 and Flex 2 on Windows XP
Author: Danny Tramnitzke

Contents

1. Starting with Red5

First we need to download the latest Red5 server from http://osflash.org/red5 . During installation it is recommended to keep the default values ( at least the rtmp ports and handling red5 as service ). After the installation start the red5 service from the windows services list.

Now you can start a browser and test the welcome page of red5 http://localhost:5080/. ( if you have chosen the http port 5080 at the installation ) If everything is ok, click on the "demos" link ( http://localhost:5080/demos/ ) and start the OFLA Demo, which is a small video streaming application. Here first connect to your red5 server by clicking on the "connect" button at the upper right corner. Right after that happened some sample videos will appear in a list. Click on one of these videos and it is streamed from your red5 server to this demo browser application.

If all this is running properly, we can start to build up our own application.

Therefore you should watch the great video tutorials here : http://www.flashextensions.com/tutorials.php The red5 section can be found at page 2. You should watch everything, which is related to the red5 server application ( which are the red5 video tutorials 1 - 18 ). But to follow building the necessary client application, they require you to have expensive adobe editor tools. At this point I've started my online voyage for some open source solutions or other tutorials dealing with open source flash clients. But however, flash applications, even there are millions of them out there, are very rare in the open source field. Additionally the development of red5 started in ActionScript 2 - times, what means, that the source code of many red5 client applications are written in AS2. Unfortunately AS2 is not completely compatible to today's AS3, which has also an effect to such red5 clients.

2. Flex 2 Editor for free !

Finnally I found some tools, which, carpentered together, made a nice free available flex 2 editor application. With that it is possible to create modern Flex 2 applications using ActionScript 3, which are accessing a red5 server.

First of all, after you have finished all red5 video tutorials mentioned before, you should create the editor, wich we will use to implement a test client application for our red5 demo service. Everything you have to do now it written here : http://www.bit-101.com/blog/?p=849 Read carefully, since I ignored first [update] part and got some trouble. Also the example for testing by calling the xtrace( ) method does not work at my system ( I don't see the trace output and I don't know where it should appear.. ), so I've tested Flex2 with ActionScript 3 with an own little application. This is explained at point 3. After you have built up your editor with that tutorial, you better should double check all paths in the template files build.xml and build.properties of both new templates ( 05 and 06 ). Pay attention to the <arg line="-source-path='..../FlashDevelop/Library' /> line in build.xml since this line is pretty hidden.

3. Flex 2 and Actionscript 3 Introduction

Open a new Flex2 Project ( Project -> New Project : Flex 2 Project ) Having done this, at the project explorer at the right side you see a general structure of your new project. Open up the App.mxml at the src folder. You see already the mx:Application tags. Between these opening and closing tags every content is written, like you write everything between <HTML> and </HTML> in an HTML file.

For your first flash application, your App.mxml should look like this : (pay attention, that in line 2 "<mx:Application ... " is no attribute "layout" ! )

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" >
  
 <mx:Script><![CDATA[
    
     public function say(message:String):void
     {
       output.text = message;
     }
    
 ]]></mx:Script>

 <mx:TextArea id="output" width="200" height="100" textAlign="center" />
 <mx:Button id="cmdButton1" label="Say Hello" click='say("Hello from Button1");'/>

</mx:Application>

As you can see, this page contains a text area and a button. Clicking on that button will call an ActionScript function. Here the similarities from Flex with AS to HTML with JS are obvious. You can compile this by clicking on the Ant-Build Button at the tool bar. After the compilation was successfull, the flex application is shown in a new tab of the editor. Additionally a html file, holding this flex application was also created, and can be opened at the deploy folder of this project.


Lets check out, how to use external ActionScript 3 classes with our mxml file. Therefore add a new folder in your src folder called myClasses. There, add a new class with the name Greeter. The class should look like this :

package myClasses 
{ 
   public class Greeter 
   { 
       //constructor 
       public function Greeter(initialName:String = "") 
       { 

           name = initialName; 
       } 
       
       //attribute 
       public var name:String; 
       
       //method 
       public function sayHello():String 
       { 

           var result:String; 
           if (name != null && name.length > 0) 

           { 
               result = "Hello there, " + name + "."; 
           } 

           else 
           { 
               result = "Hello there, anonymous."; 
           } 
           return result; 
       } 
   } 
}

As you can see, this class has a constructor method taking a String parameter. Furthermore it consists of an attribute name and a method sayHello() which returns a String.


To use this class in our App.mxml, we have to import it at the ActionScript code area. Now we can instantiate a new Greeter object called myGreeter. With that we can access the method sayHello() . To see a result on our final flex application, another button is created, which accesses another method, at which we use the Greeter class. All together, our mxml file should look like this now :

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" >
  
  <mx:Script><![CDATA[
    
      import myClasses.Greeter;
     
      public function say(message:String):void
      {
        output.text = message;
      }
     
      public function greetings():void
      {
        var myGreeter:Greeter = new Greeter("Alex");
        output.text = myGreeter.sayHello();
      }
    
  ]]></mx:Script>
 
  <mx:TextArea id="output" width="200" height="100" textAlign="center" />
 
  <mx:Button id="cmdButton1" label="Say Hello" click='say("Hello from Button1");'/>
  <mx:Button id="cmdButton2" label="Greetings" click="greetings();"/>
 
</mx:Application>


Everything, whats new is bold now.

As a result we have an application with one text area and two buttons . Pressing on the Say Hello button will call the internal say( .. ) function in our App.mxml. Pressing on button Greetings uses an instance of our Action Script class Greeter.

Now, that we have learned some basics of Flex 2 and ActionScript 3 we can go on and write a client application, which communicates with our red5 demo server, that we have created from the video tutorials earlier.

4. Flex 2 Client Application for our Red5 Server

Open a new Flex 2 project in the FlashDevelop Editor. Here place a TextInput, a TextArea and a connect-button in the App.mxml, that it is looking like this :

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
   
    <mx:Script><![CDATA[
       
        public function connect():void
        {
        }
    ]]>
       
    </mx:Script>

    <mx:TextInput id="txtConnectURL" width="200" height="22" text="rtmp://localhost/demo"/>
    <mx:TextArea id="output" width="100%" textAlign="center" />
    <mx:Button id="cmdConnect" label="Connect" click="connect();"/>
</mx:Application>

As you see, nothing happens, if the connect-button is pressed. To realize a connection to our red5 server, we need the help of two ActionScript classes, which I have found at an example application. Download these classes here : AS_red5_Connection.zip and extract the zip archive into your src folder of your project. After that you have an org.red5.as.net.events folder structure holding the Connection.as and ConnectionEvent.as class.


Now you can import both classes into your embedded ActionScript and fill the connect method, so that your embedded ActionScript code looks like this :

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init();">
   
    <mx:Script><![CDATA[
       
        import org.red5.as3.net.Connection;
        import org.red5.as3.net.events.ConnectionEvent;
       
        private var conn:Connection;

        public function init():void
        {
            conn = new Connection();
         
            // add a listener for a successful connection...
            conn.addEventListener(Connection.SUCCESS, handleSucessfulConnection);
         
            // add a listener for no successful connection...
            conn.addEventListener(Connection.DISCONNECTED, handleDisconnection);
        }
       
        public function connect():void
        {   
            if(cmdConnect.label == "Connect")
            {
                conn.setURI(txtConnectURL.text);
                conn.connect();
                cmdConnect.label = "Disconnect";
            }
            else
            {
                conn.close();
                cmdConnect.label = "Connect";
            }
        }
    ]]>

    </mx:Script>

    <mx:TextInput id="txtConnectURL" width="200" height="22" text="rtmp://localhost/demo"/>
    <mx:TextArea id="output" width="400" height="400" textAlign="center" />
    <mx:Button id="cmdConnect" label="Connect" click="connect();"/>
</mx:Application>

What we have here is a new function called init() at which a new Connection attribute with two EventListeners were added. These EventListeners are essential for ActionScript, since that way every occurred event is connected to event handlers or handle methods. Here, the function handleSucessfulConnection will be called, if a connection is established successfully. If the connection is closed the function handleDisconnection is called. In our case we have to add these two handle function, before the code above is running properly. We are doing this after two more sentences about the init() function and the new content of connect().

It is neccessary to add the EventListeners at the init() function, because that way they are active over the whole applications runtime. To call this function we have to add creationComplete="init();" at the <mx:Application .. declaration ( at line 2 ) At the connect() function it is easy to see, that our connect-button switches its label from "Connect" to "Disconnect" when we clicking on it. From the buttons label we decide whether to connect to our server or disconnect. Now we add the two handler methods for a successfull and failed / closed connection.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init();">
   
    <mx:Script><![CDATA[
      
        import org.red5.as3.net.Connection;
        import org.red5.as3.net.events.ConnectionEvent;
     
        private var conn:Connection;
       
        public function init():void
        {
            conn = new Connection();
         
            // add a listener for a successful connection...
            conn.addEventListener(Connection.SUCCESS, handleSucessfulConnection);
         
            // add a listener for no successful connection...
            conn.addEventListener(Connection.DISCONNECTED, handleDisconnection);
        }
     
        public function connect():void
        {
            if(cmdConnect.label == "Connect")
            {
                conn.setURI(txtConnectURL.text);
                conn.connect();
                cmdConnect.label = "Disconnect";
            }
            else
            {
                conn.close();
                cmdConnect.label = "Connect";
            }
        }
     
        public function handleSucessfulConnection(e:ConnectionEvent):void
        {         
            output.text += "\nConnection successful!";
        }
     
        public function handleDisconnection(e:ConnectionEvent):void
        {
            output.text += "\nConnection to " + txtConnectURL.text + " closed.";
        }
    ]]>
   
    </mx:Script>

    <mx:TextInput id="txtConnectURL" width="200" height="22" text="rtmp://localhost/demo"/>
    <mx:TextArea id="output" width="400" height="400" textAlign="center" />
    <mx:Button id="cmdConnect" label="Connect" click="connect();"/>
</mx:Application>


Now we have a running Flex application. We can connect and disconnect to our red5 server ! The next step is to call our app(double a, double b) method from the red5 demo application. Therefore we need another button calling another function:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init();">
   
    <mx:Script><![CDATA[
       
        import org.red5.as3.net.Connection;
        import org.red5.as3.net.events.ConnectionEvent;
       
        import flash.net.NetConnection;
        import flash.net.Responder; 
      
        private var conn:Connection;
        private var nc:NetConnection;
       
        public function init():void
        {
            conn = new Connection();
          
            // add a listener for a successful connection...
            conn.addEventListener(Connection.SUCCESS, handleSucessfulConnection);
          
            // add a listener for no successful connection...
            conn.addEventListener(Connection.DISCONNECTED, handleDisconnection);
        }
      
        public function connect():void
        {
            if(cmdConnect.label == "Connect")
            {
                conn.setURI(txtConnectURL.text);
                conn.connect();
                cmdConnect.label = "Disconnect";
            }
            else
            {
                conn.close();
                cmdConnect.label = "Connect";
            }
        }
      
        public function handleSucessfulConnection(e:ConnectionEvent):void
        {          
            output.text += "\nConnection successful!";
            nc = conn.getConnection();
            output.text += ("\n" + nc.uri);
        }
      
        public function handleDisconnection(e:ConnectionEvent):void
        {
            output.text += "\nConnection to " + txtConnectURL.text + " closed.";
        }
       
        public function add():void
        {
            nc.call("add", new Responder(onSuccess, onFault), 2, 3);
        }
       
        public function onSuccess(result:Object):void
        {
            output.text += "\ngot from server : " + result;
        }
       
        public function onFault(fault:Object):void
        {
            output.text += "\nfault on call , got : " + fault;
        }
       
    ]]>
   
    </mx:Script>

    <mx:TextInput id="txtConnectURL" width="200" height="22" text="rtmp://localhost/demo"/>
    <mx:TextArea id="output" width="400" height="400" textAlign="center" />
    <mx:Button id="cmdConnect" label="Connect" click="connect();"/>
    <mx:Button id="cmdAdd" label="2 + 3" click="add();"/>
</mx:Application>

First we have a new button here calling the function add(). At this function, we use an instance of a NetConnection, which we got from our successful red5 connection ( see handleSucessfulConnection(..) ). This nc object is calling the "add" function of your red5 demo service and takes after the Responder instance an arbitrary amount of parameters. But notice, that the parameters must fit the parameter definition of your red 5 server method ( in this case two numbers ) The Responder instance is handling success and fail events here. I don't know, why this is not done the same way like the connection event handling, but however, it works ! Try this App.mxml now and you can communicate finally with your red 5 demo application !

Have fun extending your application !

Pease don't hesitate to pose questions if you're running into trouble during this tutorial.

Personal tools