package { import flash.display.Sprite; import flash.events.ProgressEvent; import flash.net.Socket; publicclass SocketExample extends Sprite { privatevar socket:Socket; publicfunction SocketExample( ) { socket = new Socket( ); // Listen for when data is received from the socket server socket.addEventListener( ProgressEvent.SOCKET_DATA, onSocketData ); // Connect to the server socket.connect( "localhost", 2900 ); } privatefunction onSocketData( event:ProgressEvent ):void { trace( "Socket received " + socket.bytesAvailable + " byte(s) of data:" ); // Loop over all of the received data, and only read a byte if there // is one available while ( socket.bytesAvailable ) { // Read a byte from the socket and display it var data:int = socket.readByte( ); trace( data ); } } } }
package { import flash.display.Sprite; import flash.events.Event; import flash.events.DataEvent; import flash.net.XMLSocket; publicclass SocketExample extends Sprite { privatevar xmlSocket:XMLSocket; publicfunction SocketExample( ) { xmlSocket = new XMLSocket( ); // Connect listener to send a message to the server // after we make a successful connection xmlSocket.addEventListener( Event.CONNECT, onConnect ); // Listen for when data is received from the socket server xmlSocket.addEventListener( DataEvent.DATA, onData ); // Connect to the server xmlSocket.connect( "localhost", 2900 ); } privatefunction onConnect( event:Event ):void { xmlSocket.send( "<test/>" ); } privatefunction onData( event:DataEvent ):void { // The raw string returned from the server. // It might look something like this: // <response><test success='true'/></response> trace( event.data ); // Convert the string into XML var response:XML = new XML( event.data ); // Using E4X, access the success attribute of the "test" // element node in the response. // Output: true trace( response.test.@success ); } } }