Thursday, January 27, 2011

How to find the network disconnection at a flash client?

Issue

When the flush client only playing (not publishing) video streams, the network disconnection is not detected. When client send nothing to the server, neither NetConnection or NetStream does not receive any NetStatusEvent.

Solution

It's easy. Just issue some message from client to server.

package my.project.flash {
 
    public class MyNetConnection extends NetConnection {

        public function MyNetConnection(){
            super();
        }

        public override function connect(command:String, ... args):void {
            super.connect(command);
            addEventListener(NetStatusEvent.NET_STATUS, onStatus);
        }

        public function onStatus(event:NetStatusEvent):void {
            if (event.info.code == "NetConnection.Connect.Success"){
                onConnect(event);
            } else {
                onDisconnect(event);
            }
        }

        public function onConnect(event:NetStatusEvent):void { 
            setupPingTimer();
        }
  
        public function onDisconnect(event:NetStatusEvent):void {
            // doSomethingOnDisconnect();
        }

        public function setupPingTimer():void {
            var pingTimer:Timer = new Timer(1000);
            pingTimer.addEventListener(TimerEvent.TIMER, sendPing);
            pingTimer.start();
        }
    
        public function sendPing(event:TimerEvent):void {
            call("ping", null); // (no response)
        }
    }
}

No comments:

Post a Comment