Source

FlSock / FlSock.as

Full commit
package {

    import flash.external.ExternalInterface;    
    import flash.display.LoaderInfo;    
    import flash.events.ProgressEvent;  
    import flash.events.IOErrorEvent;   
    import flash.events.ErrorEvent; 
    import flash.events.Event;  
    import flash.display.Sprite;
    import flash.net.Socket;
    
    public class FlSock extends Sprite {
        
        protected var host:String;
        protected var port:int;
        protected var term:String = String.fromCharCode(1);
        protected var messageStart:String = 'm';
        protected var sock:Socket;
        protected var data:String = '';
        
        public function FlSock() {
            super();
            sock = new Socket();
            sock.addEventListener(Event.CONNECT, connectHandle);
            sock.addEventListener(Event.CLOSE, closeHandle);
            sock.addEventListener(ErrorEvent.ERROR, errorHandle);
            sock.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandle);
            sock.addEventListener(ProgressEvent.SOCKET_DATA, dataHandle);
            loadParameters();
            sock.connect(host, port);
        }
        
        protected function loadParameters():void {
            try {
                var params:Object = LoaderInfo(loaderInfo).parameters;
                if (params.hasOwnProperty('host')) {
                    host = String(params['host']);
                }
                if (params.hasOwnProperty('port')) {
                    port = int(params['port']);
                }
            } catch (e:Error) {
            }
        }
        
        protected function connectHandle(e:Event):void {
            ExternalInterface.addCallback('sendMessage', sendMessage);
            ExternalInterface.call('connectHandle');
        }
        
        protected function closeHandle(e:Event):void {
        }
        
        protected function errorHandle(e:ErrorEvent):void {
        }
        
        protected function ioErrorHandle(e:IOErrorEvent):void {
        }
        
        protected function dataHandle(e:ProgressEvent):void {
            data += sock.readUTFBytes(e.bytesLoaded);
            while(data.indexOf(this.term) >= 0) {
                var message:String = data.split(term, 1)[0];
                data = data.slice(message.length + term.length);
                if (message) {
                    messageHandle(message);
                }
            }
        }
        
        protected function messageHandle(message:String):void {
            ExternalInterface.call('handleMessage', message);
        }
        
        protected function sendMessage(message:String):void {
            this.sock.writeUTFBytes(messageStart + message + term);
        }
    }
}