var processFunc:Function = stateMap[ currentState ]; processFunc( ); // Invoke the appropriate processing function
完整代码如下:
+展开
-ActionScript
package { import flash.display.Sprite; import flash.events.ProgressEvent; import flash.net.Socket; import flash.utils.ByteArray; publicclass SocketExample extends Sprite { // The state constants to describe the protocol publicconst DETERMINE_VERSION:int = 0; publicconst RECEIVE_CHALLENGE:int = 1; publicconst NORMAL:int = 2; // Maps a state to a processing function privatevar stateMap:Object; // Keeps track of the current protocol state privatevar currentState:int; privatevar socket:Socket; publicfunction SocketExample( ) { // Initialzes the states map stateMap = new Object( ); stateMap[ DETERMINE_VERSION ] = readVersion; stateMap[ RECEIVE_CHALLENGE ] = readChallenge; stateMap[ NORMAL ] = readNormalProtocol; // Initialze the current state currentState = DETERMINE_VERSION; // Create and connect the socket socket = new Socket( ); socket.addEventListener( ProgressEvent.SOCKET_DATA, onSocketData ); socket.connect( "localhost", 2900 ); } privatefunction onSocketData( event:ProgressEvent ):void { // Look up the processing function based on the current state var processFunc:Function = stateMap[ currentState ]; processFunc( ); } privatefunction readVersion( ):void { // Step 1 - read the version from the server var version:int = socket.readInt( ); // Once the version is read, the next state is receiving // the challenge from the server currentState = RECEIVE_CHALLENGE; // Step 2 - write the version back to the server socket.writeInt( version ); socket.flush( ); } privatefunction readChallenge( ):void { // Step 3 - read the 8 byte challenge into a byte array var bytes:ByteArray = new ByteArray( ); socket.readBytes( bytes, 0, 8 ); // After the challenge is received, the next state is // the normal protocol operation currentState = NORMAL; // Step 4 - write the bytes back to the server socket.writeBytes( bytes ); socket.flush( ); } privatefunction readNormalProtocol( ):void { // Step 5 - process the normal socket messages here now that // that handshaking process is complete } } }