<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" 
                       xmlns:s="library://ns.adobe.com/flex/spark" 
                       xmlns:mx="library://ns.adobe.com/flex/halo"
                       applicationComplete="init()" width="218" height="354" viewSourceURL="srcview/index.html">
    <fx:Script>
        <![CDATA[
            import flash.events.Event;
            import flash.events.IOErrorEvent;
            import flash.events.ProgressEvent;
            import flash.net.Socket;
            
            [Bindable] private var socket:Socket;
            
            private function init():void
            {
                socket = new Socket;
                socket.addEventListener(Event.CONNECT, socketConnectHandler);
                socket.addEventListener(Event.CLOSE, socketCloseHandler);
                socket.addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
                socket.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
            }
            
            private function socketConnectHandler(event:Event):void
            {
                log.text += 'connected\n';
            }
            
            private function socketCloseHandler(event:Event):void
            {
                log.text += 'disconnected\n';
                btn.selected = false;
            }
            
            private function socketDataHandler(event:ProgressEvent):void
            {
                var bytes:ByteArray = new ByteArray;
                socket.readBytes(bytes);
                log.text += bytes + '\n';
            }
            
            private function ioErrorHandler(event:IOErrorEvent):void
            {
                log.text += event.text + '\n';
                btn.selected = false;
            }
            
            private function btnClickHandler():void
            {
                if(socket.connected)
                {
                    socket.close();
                    log.text += 'closed\n';
                }
                else
                    socket.connect( hostInput.text, int(portInput.text) );
            }
        ]]>
    </fx:Script>
    
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
    
    <s:ToggleButton id="btn" label="{btn.selected ? 'Disconnect':'Connect'}" click="btnClickHandler()" width="128" x="81" y="70"/>
    <s:TextArea id="log" x="8" y="99" height="222" width="202"/>
    <s:Label x="10" y="14" text="IP address:"/>
    <s:TextInput id="hostInput" x="81" y="9" text="127.0.0.1" enabled="{!btn.selected}"/>
    <s:Label x="50" y="44" text="port:"/>
    <s:TextInput id="portInput" x="81" y="39" text="8888" enabled="{!btn.selected}" restrict="0-9"/>
</s:WindowedApplication>