package
{ import flash.display.Sprite; import flash.events.ProgressEvent; import flash.net.Socket; import flash.utils.ByteArray; /** * * 三次握手连接socket * 来源socket编程 */ public class SocketHandshake extends Sprite { public const DETERMINE_VERSION:int = 0; public const RECEIVE_CHALLENGE:int = 1; public const NORMAL:int = 2; private var stateMap:Object; private var currentState:int; private var socket:Socket; public function SocketHandshake( ) { stateMap = new Object( ); stateMap[DETERMINE_VERSION] = readVersion; stateMap[RECEIVE_CHALLENGE] = readChallenge; stateMap[NORMAL] = readNormalProtocol; currentState = DETERMINE_VERSION; socket = new Socket( ); socket.addEventListener( ProgressEvent.SOCKET_DATA, onSocketData ); socket.connect( "localhost", 9000 ); trace(currentState); } private function onSocketData( event:ProgressEvent ):void { trace(currentState); var processFunc:Function = stateMap[currentState]; processFunc( ); } private function readVersion( ):void { try { var version:int = socket.readInt(); trace(version); } catch (error:Error) { trace("error:"+error); } currentState = RECEIVE_CHALLENGE; socket.writeInt( version ); socket.flush( ); } private function readChallenge( ):void { var bytes:ByteArray = new ByteArray( ); socket.readBytes( bytes, 0, 8 ); currentState = NORMAL; socket.writeBytes( bytes ); socket.flush( ); } private function readNormalProtocol( ):void { } } }