码迷,mamicode.com
首页 > 其他好文 > 详细

[ActionScript 3.0] AS3.0 Socket通信实例

时间:2016-08-12 14:55:49      阅读:607      评论:0      收藏:0      [点我收藏+]

标签:

以下类是充当Socket服务器的例子

 

package
{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.events.ProgressEvent;
    import flash.events.ServerSocketConnectEvent;
    import flash.net.ServerSocket;
    import flash.net.Socket;
    import flash.text.TextField;
    import flash.text.TextFieldType;
    import flash.utils.ByteArray;
    
    /**
     * @author:Frost.Yen
     * @E-mail:871979853@qq.com
     * @create:    2016-7-20 下午12:37:30
     *
     */
    public class SocketServer extends Sprite
    {
        private var serverSocket:ServerSocket = new ServerSocket();
        private var clientSocket:Socket;
        private var localIP:TextField;
        private var localPort:TextField;
        private var logField:TextField;
        private var message:TextField;
        private var _clients:Array = [];

        public function SocketServer()
        {
            setupUI();
        }
        //当客户端成功连接服务端
        private function onConnect( event:ServerSocketConnectEvent):void
        {
            clientSocket = event.socket;
            clientSocket.addEventListener( ProgressEvent.SOCKET_DATA, onClientSocketData );
            _clients.push(clientSocket);
            trace(_clients.length);
            log( "Connection from " + clientSocket.remoteAddress + ":" + clientSocket.remotePort );
        }
        //当有数据通信时
        private function onClientSocketData( event:ProgressEvent ):void
        {
            var buffer:ByteArray = new ByteArray();
            var client:Socket = event.currentTarget as Socket;
            client.readBytes( buffer, 0, client.bytesAvailable );
            log( "Received from Client"+ clientSocket.remoteAddress + ":" + clientSocket.remotePort+"-- " + buffer.toString() );
        }
        //绑定服务器ip 开始监听端口
        private function bind( event:Event ):void
        {
            if( serverSocket.bound ) 
            {
                serverSocket.close();
                serverSocket = new ServerSocket();
                
            }
            serverSocket.bind( parseInt( localPort.text ), localIP.text );
            serverSocket.addEventListener( ServerSocketConnectEvent.CONNECT, onConnect );
            serverSocket.listen();
            log( "Bound to: " + serverSocket.localAddress + ":" + serverSocket.localPort );
        }
        //服务器端向所有客户端发送数据
        private function send( event:Event ):void
        {
            try
            {
                if (_clients.length == 0)
                {
                    log(‘没有连接‘);
                    return;
                }
                for (var i:int = 0; i < _clients.length; i++) 
                {
                    var item:Socket = _clients[i] as Socket;
                    if (!item) continue;
                    item.writeUTFBytes(message.text);
                    item.flush();
                }
            }
            catch ( error:Error )
            {
                log( error.message );
            }
        }
        // 输出日志
        private function log( text:String ):void
        {
            logField.appendText( text + "\n" );
            logField.scrollV = logField.maxScrollV;
            trace( text );
        }
        //设置皮肤
        private function setupUI():void
        {
            localIP = createTextField( 10, 10, "Local IP", "0.0.0.0");
            localPort = createTextField( 10, 35, "Local port", "0" );
            createTextButton( 170, 60, "Bind", bind );
            message = createTextField( 10, 85, "Message", "send message to Client." );
            createTextButton( 170, 110, "Send", send );
            logField = createTextField( 10, 135, "Log", "", false, 200 )
            
            this.stage.nativeWindow.activate();
        }
        private function createTextField( x:int, y:int, label:String, defaultValue:String = ‘‘, editable:Boolean = true, height:int = 20 ):TextField
        {
            var labelField:TextField = new TextField();
            labelField.text = label;
            labelField.type = TextFieldType.DYNAMIC;
            labelField.width = 100;
            labelField.x = x;
            labelField.y = y;
            
            var input:TextField = new TextField();
            input.text = defaultValue;
            input.type = TextFieldType.INPUT;
            input.border = editable;
            input.selectable = editable;
            input.width = 280;
            input.height = height;
            input.x = x + labelField.width;
            input.y = y;
            
            this.addChild( labelField );
            this.addChild( input );
            
            return input;
        }
        private function createTextButton( x:int, y:int, label:String, clickHandler:Function ):TextField
        {
            var button:TextField = new TextField();
            button.htmlText = "<u><b>" + label + "</b></u>";
            button.type = TextFieldType.DYNAMIC;
            button.selectable = false;
            button.width = 180;
            button.x = x;
            button.y = y;
            button.addEventListener( MouseEvent.CLICK, clickHandler );
            
            this.addChild( button );
            return button;
        }     
    }
}

 

以下类是充当客户端的例子

 

package
{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.IOErrorEvent;
    import flash.events.MouseEvent;
    import flash.events.ProgressEvent;
    import flash.net.Socket;
    import flash.text.TextField;
    import flash.text.TextFieldType;
    import flash.utils.ByteArray;
    
    /**
     * @author:Frost.Yen
     * @E-mail:871979853@qq.com
     * @create:    2016-7-20 下午12:44:52
     *
     */
    public class SocketClient extends Sprite
    {
        private var clientSocket:Socket = new Socket();
        private var localIP:TextField;
        private var localPort:TextField;
        private var logField:TextField;
        private var message:TextField;
        private var _clients:Array = [];
        public function SocketClient()
        {
            setupUI();

        }
        private function onConnect( event:Event ):void
        {
            log(‘成功连接服务器!‘);
            log( "Connection from " + clientSocket.remoteAddress + ":" + clientSocket.remotePort );
        }
        private function onClientSocketData( event:ProgressEvent):void
        {
            var buffer:ByteArray = new ByteArray();
            clientSocket.readBytes( buffer, 0, clientSocket.bytesAvailable );
            log( "Send: " + buffer.toString() );
        }
        private function collect(e:Event):void
        {
            bind(localIP.text, parseInt( localPort.text ));
        }
        public function bind(host:String = "localhost", port:Number = 9080):void
        {
            log(‘开始连接服务器!‘);
            clientSocket.connect(host, port);
            clientSocket.addEventListener(Event.CONNECT, onConnect);//监听连接事件
            clientSocket.addEventListener(IOErrorEvent.IO_ERROR,onError);
            clientSocket.addEventListener(ProgressEvent.SOCKET_DATA,onSocketData);
        }
        private function onError(e:IOErrorEvent):void
        {
            log(e.toString());
        }
        //向服务器发送数据
        private function send( event:Event ):void
        {
            try
            {
                if( clientSocket != null && clientSocket.connected )
                {
                    clientSocket.writeUTFBytes( message.text );
                    clientSocket.flush(); 
                    //log( "Sent message to " + clientSocket.remoteAddress + ":" + clientSocket.remotePort );
                }
                else log("No socket connection.");
            }
            catch ( error:Error )
            {
                log( error.message );
            }
        }
        private function onSocketData(e:ProgressEvent):void
        {
            var buffer:String = clientSocket.readUTFBytes(clientSocket.bytesAvailable );
            log( "Received from Server:" + buffer );
        }
        private function log( text:String ):void
        {
            logField.appendText( text + "\n" );
            logField.scrollV = logField.maxScrollV;
        }
        
        private function setupUI():void
        {
            localIP = createTextField( 10, 10, "Local IP", "0.0.0.0");
            localIP.text = ‘localhost‘;
            localPort = createTextField( 10, 35, "Local port", "0" );
            createTextButton( 170, 60, "Collect", collect );
            message = createTextField( 10, 85, "Message", "Lucy can‘t drink milk." );
            createTextButton( 170, 110, "Send", send );
            logField = createTextField( 10, 135, "Log", "", false, 200 )
            this.stage.nativeWindow.activate();
        }
        
        private function createTextField( x:int, y:int, label:String, defaultValue:String = ‘‘, editable:Boolean = true, height:int = 20 ):TextField
        {
            var labelField:TextField = new TextField();
            labelField.text = label;
            labelField.type = TextFieldType.DYNAMIC;
            labelField.width = 100;
            labelField.x = x;
            labelField.y = y;
            
            var input:TextField = new TextField();
            input.text = defaultValue;
            input.type = TextFieldType.INPUT;
            input.border = editable;
            input.selectable = editable;
            input.width = 280;
            input.height = height;
            input.x = x + labelField.width;
            input.y = y;
            
            this.addChild( labelField );
            this.addChild( input );
            
            return input;
        }
        
        private function createTextButton( x:int, y:int, label:String, clickHandler:Function ):TextField
        {
            var button:TextField = new TextField();
            button.htmlText = "<u><b>" + label + "</b></u>";
            button.type = TextFieldType.DYNAMIC;
            button.selectable = false;
            button.width = 180;
            button.x = x;
            button.y = y;
            button.addEventListener( MouseEvent.CLICK, clickHandler );
            
            this.addChild( button );
            return button;
        }        

    }
}

 

[ActionScript 3.0] AS3.0 Socket通信实例

标签:

原文地址:http://www.cnblogs.com/frost-yen/p/5764684.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!