2014-04-07 22 views
1

我希望使用遠程SharedObject,所以我創建了一個簡單的腳本來測試這些技術。當我跑到下面的代碼爲SWF的兩個實例,這兩種情況下輸出1,這是不正確的,因爲第二個實例是應該輸出2如何在AS3和Red5中使用遠程SharedObject

import flash.net.SharedObject; 
import flash.events.SyncEvent; 

var nc:NetConnection; 
var so:SharedObject; 

nc = new NetConnection(); 
nc.client = { onBWDone: function():void{} }; 
nc.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus); 
nc.connect("rtmp://localhost:1935/live"); 

var t = new TextField(); 
addChild(t); 

function onNetStatus(event:NetStatusEvent):void{ 
    if(event.info.code == "NetConnection.Connect.Success"){ 
     so = SharedObject.getRemote("shObj",nc.uri); 
     so.connect(nc); 
     if (!(so.data.total > 0 && so.data.total<1000)) {// undefined 
      so.data.total=1; 
     } else so.data.total=2; 
     t.text=so.data.total; 
    } 
} 

我錯過了一些東西?我是否需要對Flash或Red5進行一些特殊設置?我需要創建一個特殊的目錄嗎?我必須使用特殊的事件監聽器嗎?任何人都可以爲我糾正代碼嗎?


(2014年4月9日)

當我使用的事件偵聽器像下文中,我得到了兩個實例空白屏幕,因爲我預期至少所述第二屏幕以顯示「2這是奇怪」。有人可以解釋這種行爲嗎?

import flash.net.SharedObject; 
import flash.events.SyncEvent; 

var nc:NetConnection; 
var so:SharedObject; 

nc = new NetConnection(); 
nc.client = { onBWDone: function():void{} }; 
nc.addEventListener(NetStatusEvent.NET_STATUS, onNetStatus); 
nc.connect("rtmp://localhost:1935/live"); 

var t = new TextField(); 
addChild(t); 

function onNetStatus(event:NetStatusEvent):void{ 
    if(event.info.code == "NetConnection.Connect.Success"){ 
     so = SharedObject.getRemote("shObj",nc.uri); 
     so.addEventListener(SyncEvent.SYNC,syncHandler); 
     so.connect(nc); 
     so.setProperty("total",2); 
    } 
} 

function syncHandler(event:SyncEvent):void{ 
    if (so.data.total) { 
     t.text = so.data.total; 
    } 
} 
+0

我有一組使用SO的,我只是在過去的寫完整的例子天:https://github.com/Red5/red5-websocket-chat-as3 https://github.com/Red5/red5-websocket-chat –

回答

2

基本上是使用共享對象,我會建議工作拆分爲三個獨立的部分。

  1. 附加事件監聽器,並連接到共享對象

    function onNetStatus(event:NetStatusEvent):void 
    { 
        if(event.info.code == "NetConnection.Connect.Success") 
        { 
         so = SharedObject.getRemote("shObj",nc.uri); 
         so.addEventListener(SyncEvent.SYNC,syncHandler); //add event listener for Shared Object 
         so.connect(nc); 
        } 
    } 
    
  2. 完成事件處理方法,以反映在共享對象的值改變

    /* This function is called whenever there is change in Shared Object data */ 
    function syncHandler(event:SyncEvent):void 
    { 
        if(so.data.total) //if total field exists in the Shared Object 
         trace(so.data.total); 
    } 
    
  3. 變化的數據共享對象:
    這裏使用共享對象的setProperty方法。當您需要更改值(也許在按一下按鈕或某些事件的發生),調用此方法

    /* This function writes values to the Shared Object */ 
    function changeValue(newValue:String) 
    { 
        so.setProperty("total",newValue); 
    } 
    
相關問題