Primeiramente vamos saber o que é FMS (Flash Media Server)
O Flash Media Server é um servidor de Streaming, nele é possível
fazer:
· Aplicações de áudio e vídeo interativas
· Mídia em tempo real
· Vídeo e áudio "on Demand"
· Aplicações de colaboração
· Chats via webcam
Ele é muito usado em aplicações feitas em Flash, mais nós podemos
também usá-lo em aplicações feitas em Flex.
A primeira coisa a se fazer é baixar o instalador:
https://www.adobe.com/cfusion/tdrc/index.cfm?product=flashmediaserver
Ele é gratuito para desenvolvedores, dá até 10 conexões simultãneas
sem cobrar nada.
Após a instalação vamos começar a programação:
primeiro no Flex:
Crie um arquivo chamado flexFCS.mxml
nele escreva o seguinte código
<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" width="650"
height="516" creationComplete="init();" backgroundColor="#e6e6e6">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import flash.net.*;
import flash.events.*;
import flash.utils.*;
import mx.controls.*;
import mx.core.UIComponent;
// Current release of FMS only understands AMF0 so tell
Flex to
// use AMF0 for all NetConnection, NetStream,
and SharedObject
objects.
NetConnection.defaultObjectEncoding =
flash.net.ObjectEncoding.AMF0;
//NetStream.defaultObjectEncoding =
flash.net.ObjectEncoding.AMF0;
SharedObject.defaultObjectEncoding =
flash.net.ObjectEncoding.AMF0;
// echoResponder is used when nc.call("echo",
echoResponder ...)
is called.
private var echoResponder:Responder = new
Responder(echoResult,
echoStatus);
// SharedObject and NetConnection vars
private var nc:NetConnection;
public var ro:SharedObject;
private function init():void
{
writeln("Initializing application... in
player: " +
flash.system.Capabilities.version + "\n");
// create new connection to FMS and add
listeners
nc = new NetConnection();
nc.addEventListener(NetStatusEvent.NET_STATUS, netStatus);
nc.addEventListener(SecurityErrorEvent.SECURITY_ERROR,
netSecurityError);
}
/**
* connect is called whenever the connectButton is
pressed
* and decides what to do based on the current label of
the
button.
* NOTE: the rtmp address is in this function. Change
it if
you need to.
*/
private function connect():void
{
if(userName.text == ""){
Alert.show("Please enter a user name.");
return;
}
switch(connectButton.label){
case "Connect":
connectButton.label = "Wait";
connectButton.enabled = false;
nc.connect("rtmp://localhost/chat_test", userName.text);
nc.client = this;
break;
case "Disconnect":
connectButton.label = "Connect";
connectButton.enabled = true;
nc.close();
break;
}
}
private function
netSecurityError(event:SecurityErrorEvent):void {
writeln("netSecurityError: " + event);
}
/**
* This method could be named anything - even
onStatus. I've named
it
* netStatus as in Dave Simmons example. In the
docs they use the
* name netStatusHandler. Instead of receiving
an information
object
* it is passed an event that contains the
information object.
*/
private function
netStatus(event:NetStatusEvent):void
{
// Write out information about
connection events:
writeln("netStatus: " + event);
var info:Object = event.info;
for(var p:String in info) {
writeln(p + " : " + info[p]);
}
writeln("");
switch (info.code)
{
case
"NetConnection.Connect.Success" :
connectButton.label =
"Disconnect";
connectButton.enabled = true;
sendButton.enabled = true;
writeln("Connecting non-persistent
Remote
SharedObject...\n");
ro =
SharedObject.getRemote("ChatUsers", nc.uri);
if(ro){
ro.addEventListener(SyncEvent.SYNC, OnSync);
ro.connect(nc);
ro.client =
this; // refers to the scope of application and
public funtions
}
getServerTime(); // get
local time
break;
case
"NetConnection.Connect.Closed" :
connectButton.label =
"Connect";
connectButton.enabled = true;
sendButton.enabled = false;
break;
case
"NetConnection.Connect.Failed" :
break;
case
"NetConnection.Connect.Rejected" :
break;
default :
//statements
break;
}
}
private function OnSync(event:SyncEvent):void
{
// Show the ChangeList:
var info:Object;
var currentIndex:Number;
var currentNode:Object;
var changeList:Array = event.changeList;
var temp:Array = new Array();
writeln("---- Shared Object Data
-----");
for(var p:String in ro.data){
writeln("OnSync> RO: " + p + ":
" + ro.data[p]);
temp.push(ro.data[p]);
}
this.usersList.dataProvider = temp;
//update list of users
for (var i:Number=0; i <
changeList.length; i++)
{
info = changeList[i];
for (var k:String in info){
writeln("OnSync>
changeList[" + i + "]." + k + ": " + info[k]);
}
}
}
/** echoResult is called when the echoResponder
gets a result from
the nc.call("echoMessage"..) */
private function echoResult(msg:String):void{
writeln("echoResult: " + msg + "\n");
this.serverTime.text = msg;
}
/** echoResult is called when the echoResponder gets a
error
after a nc.call("echoMessage"..) */
private function echoStatus(event:Event):void{
writeln("echoStatus: " + event);
}
/** sendMessage is called when the sendButton
is pressed to test
ns.send */
private function sendMessage():void{
// call our remote function and send
the message to all connected
clients
nc.call("msgFromClient", null,
sendMessageInput.text);
sendMessageInput.text = "";
}
/** get server tme */
private function getServerTime():void{
nc.call("getServerTime", echoResponder,
sendMessageInput.text);
}
/** showMessage is the function called by the
inStream. See the
netStatus function */
public function showMessage(msg:String):void{
writeln("showMessage: " + msg + "\n");
}
public function setUserID(msg:Number):void{
writeln("showMessage: " + msg + "\n");
}
public function setHistory(msg:String):void{
writeln("showHistory: " + msg + "\n");
}
public function msgFromSrvr(msg:String):void{
writeMessage(msg);
}
/**
* writeln writes text into the traceArea
TextArea instead of
using trace.
* Note to get scrolling to the bottom of the
TextArea to work
validateNow()
* must be called before scrolling.
*/
public function writeln(msg:String):void{
traceArea.text += msg + "\n";
traceArea.validateNow();
traceArea.verticalScrollPosition =
traceArea.maxVerticalScrollPosition;
}
/**
* writeMessage writes text into the main chat
text area
*/
public function writeMessage(msg:String):void{
messageArea.text += msg + "\n";
messageArea.validateNow();
messageArea.verticalScrollPosition =
messageArea.maxVerticalScrollPosition;
}
]]>
</mx:Script>
<mx:List width="127" height="210" x="513" y="66" id="usersList"/>
<mx:TextArea width="495" height="210" id="messageArea"
wordWrap="true" x="10" y="66"/>
<mx:TextInput text="hello" id="sendMessageInput" width="366" x="77"
y="284"/>
<mx:Button label="Send" id="sendButton" enabled="false"
click="sendMessage();" x="451" y="284"/>
<mx:TextInput id="serverTime" width="243" x="397" y="10"/>
<mx:Button label="Connect" id="connectButton" click="connect();"
x="212" y="10" width="90"/>
<mx:TextInput x="10" y="10" width="194" id="userName"/>
<mx:TextArea width="630" height="156" id="traceArea" wordWrap="true"
x="10" y="350"/>
<mx:Label x="10" y="324" text="Trace Window" fontWeight="bold"/>
<mx:Label x="10" y="40" text="Message Window" fontWeight="bold"/>
<mx:Label x="513" y="40" text="Users" fontWeight="bold"/>
<mx:Label x="319" y="12" text="Local Time:"/>
<mx:Label x="10" y="286" text="Message:"/>
</mx:Canvas>
Agora vamos fazer uma tela pra abrir essa outra tela.
Crie o arquivo main.mxml
nele escreva o seguinte código
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute" xmlns:ns1="*" viewSourceURL="srcview/index.html">
<ns1:flexFCS y="10" horizontalCenter="0">
</ns1:flexFCS>
</mx:Application>
Agora a parte Flex está pronta. Vamos mexer agora com a programação
para o FMS.
No servidor FMS trabalhamos com arquivos .asc, Action Script
Communication
Crie um arquivo main.asc e digite o seguinte código:
Client.prototype.getServerTime = function(msg){
var now = new Date();
return now.toString();
}
application.onAppStart = function()
{
trace("Begin sharing text");
// Get the server shared object 'users_so'
application.users_so = SharedObject.get("ChatUsers");
// Initialize the history of the text share
application.history = "";
// Initialize the unique user ID
application.nextId = 0;
}
application.onConnect = function(newClient, userName)
{
// Make this new client's name the user's name
newClient.name = userName;
// Create a unique ID for this user while incrementing the
// application.nextID.
newClient.id = "u" + application.nextId++;
// Update the 'users_so' shared object with the user's name
application.users_so.setProperty(newClient.name, userName);
// Accept the client's connection
application.acceptConnection(newClient);
// Call the client function 'setHistory,' and pass
// the initial history
newClient.call("setHistory", null, application.history);
// The client will call this function to get the server
// to accept the message, add the user's name to it, and
// send it back out to all connected clients.
newClient.msgFromClient = function(msg) {
msg = userName + ": " + msg + "\n";
application.history += msg;
application.users_so.send("msgFromSrvr", msg);
}
}
application.onDisconnect = function(client)
{
trace("disconnect: " + client.name);
application.users_so.setProperty(client.name, null);
}
Vá no diretório de instalação do FMS (Ex.: C:\Arquivos de Programas
\Macromedia\Flash Media Server 2\)
abra o diretório applications
crie uma pasta chamada chat_test e dentro dela coloque o arquivo
main.asc que acabou de criar
Vá em Iniciar > Programas > Macromedia > Flash Media Server 2 >
Management Console
Coloque o login e senha que colocou na instalação.
Na primeira tela na parte de baixo tem um combo onde está escrito New
Instance
Clique nele e selecione a pasta que acabou de criar "chat_test"
Agora sua aplicação já está carregada no FMS.
Agora coloque os swfs gerados pelos arquivos mxml e coloque em um
servidor qualquer.
Usei aqui o php (só como exemplo)
crieu uma pasta dentro de www chamada chatFlex e coloquei os swfs
dentro dela
Agora é só abrir http://localhost/chatFlex/main.swf
Ta aí um chat em Flex e FMS.
Qualquer dúvida tamos aí
On Sep 3, 7:09 am, Pablo Faria <[EMAIL PROTECTED]> wrote:
> Eu consegui fazer um chat. Pra isso usei FMS. É bem fácil
> To escrevendo um artigo pra colocar no meu blog, passo a passo como
> fazer
>
> http://javapablo.blogspot.com/
>
> Quando tiver terminado eu te respondo denovo
>
> Valeu
>
> On Sep 1, 11:25 am, Alan Granadeiro <[EMAIL PROTECTED]>
> wrote:
>
> > Galera,
>
> > A um tempo atras na lista tinha alguem desenvovlendo um chat em Flex.
>
> > Alguem sabe se a pessoa conseguiu? Usou HTTP?
>
> > Forte abraço,
>
> > Alan de Melo Granadeiro
> > Desenvovledor Web
>
> > Flickr agora em português. Você clica, todo mundo
> > vê.http://www.flickr.com.br/
--~--~---------~--~----~------------~-------~--~----~
Você recebeu esta mensagem porque está inscrito na lista "flexdev"
Para enviar uma mensagem, envie um e-mail para [email protected]
Para sair da lista, envie um email em branco para [EMAIL PROTECTED]
Mais opções estão disponíveis em http://groups.google.com/group/flexdev
-~----------~----~----~----~------~----~------~--~---