[ActionScript 3.0] AS3.0 简单封装Socket的通信

Socket服务器

package com.controls.socket
{
    import com.models.events.AppEvent;
    import com.models.events.AppEventDispatcher;
    import com.models.util.Config;
    
    import flash.events.Event;
    import flash.events.ProgressEvent;
    import flash.events.ServerSocketConnectEvent;
    import flash.net.ServerSocket;
    import flash.net.Socket;
    import flash.utils.ByteArray;

    /**
     * @author Frost.Yen
     * @email 871979853@qq.com
     * @build 2016-8-8 下午8:35:00
     */
    public class SocketServer
    {
        private var _serverSocket:ServerSocket = new ServerSocket();
        private var _clients:Array=[];//客户端数组
        private var _data:String;
        private static var _instance:SocketServer;
        public function SocketServer(s:S)
        {
        }
        public static function getInstance():SocketServer
        {
            if(!_instance){
                _instance = new SocketServer(new S());
            }
            return _instance;
        }
        /**
         * 绑定服务端ip和端口
         * @localPort 端口
         * @localAddress ip地址
         */
        public function bind(localPort:int,localAddress:String):void
        {
            if( _serverSocket.bound ) 
            {
                _serverSocket.close();
                _serverSocket = new ServerSocket();
            }
            _serverSocket.bind( localPort, localAddress);
            _serverSocket.addEventListener( ServerSocketConnectEvent.CONNECT, onConnect );
            _serverSocket.addEventListener(Event.CLOSE,onClose);
            _serverSocket.listen();
            log( "Bound to: " + _serverSocket.localAddress + ":" + _serverSocket.localPort );
        }
        /**
         * 客户端成功连接服务器
         */
        private function onConnect( event:ServerSocketConnectEvent):void
        {
            var clientSocket:Socket = event.socket;
            clientSocket.addEventListener( ProgressEvent.SOCKET_DATA, onClientSocketData );
            _clients.push(clientSocket);
       clientSocket.addEventListener(Event.CLOSE,onCloseClient);
            log( "Connection from " + clientSocket.remoteAddress + ":" + clientSocket.remotePort );
            //trace(_clients.length,"_clients.length",Config.clientNum,"Config.clientNum");
            if(_clients.length == Config.clientNum){
                log("所有客户端连接成功,共"+_clients.length+"台");
                AppEventDispatcher.getInstance().dispatchEvent(new AppEvent(AppEvent.CONNECT_SUCCEED));
            }
        }
        
        private function onClose(e:Event):void
        {
            log( "Connection Faild " );
        }
     private function onCloseClient(e:Event):void
        {
            for (var clt:int=0;clt<_clients.length;clt++){
                if(_clients[clt].remoteAddress==e.target.remoteAddress&&_clients[clt].remotePort==e.target.remotePort){
                    var msgObj:Object=_clientDic[_clients[clt].remoteAddress+_clients[clt].remotePort];
                    delete _clientDic[_clients[clt].remoteAddress+_clients[clt].remotePort];
                    _clients.splice(clt,1); 
                    if(msgObj){
                        for each(var clt2:Socket in _clients){
                            clt2.writeUTFBytes("消息:-----");
                            clt2.flush();                        
                        }
                    }
                    msgObj=null;
                    
                    log("\n"+ e.target.remoteAddress+":"+e.target.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 );
            _data = buffer.toString();
            AppEventDispatcher.getInstance().dispatchEvent(new AppEvent(AppEvent.CLIENT_DATA,buffer));
            log( "Received from Client"+ client.remoteAddress + ":" + client.remotePort+"-- " + buffer.toString() );
        }
        /**
         * 服务器向客户端发送信息
         */
        public function send(obj:Object):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(JSON.stringify(obj)+"\n");
                    item.flush();
                }
            }catch ( error:Error )
            {
                log( error.message );
            }
        }
        public function log(message:String):void
        {
            //trace(message);
        }

        public function get data():String
        {
            return _data;
        }

    }
}
class S{};

 

 

Socket客户端

package com.controls
{
    import com.models.events.AppEvent;
    import com.models.events.AppEventDispatcher;
    
    import flash.events.Event;
    import flash.events.IOErrorEvent;
    import flash.events.ProgressEvent;
    import flash.net.Socket;
    import flash.utils.ByteArray;

    /**
     * @author Frost.Yen
     * @email 871979853@qq.com
     * @build 2016-8-9 下午5:55:19
     */
    public class SocketClient
    {
        private var _client:Socket = new Socket();
        private static var _instance:SocketClient;
        public function SocketClient(s:S)
        {
        }
        public static function getInstance():SocketClient
        {
            if(!_instance){
                _instance = new SocketClient(new S());
            }
            return _instance;
        }
        /**
         * 开始连接服务器
         * @param host ip地址
         * @param port 端口
         */
        public function collect(host:String,port:int):void
        {
            log('开始连接服务器!');
            trace(host,port);
            _client.connect(host, port);
            _client.addEventListener(Event.CONNECT, onConnect);//监听连接事件
            _client.addEventListener(IOErrorEvent.IO_ERROR,onError);
            _client.addEventListener(ProgressEvent.SOCKET_DATA,onSocketData);
        }
        /**
         * 连接服务器成功
         */
        private function onConnect( event:Event ):void
        {
            log('成功连接服务器!');
            log( "Connection from " + _client.remoteAddress + ":" + _client.remotePort );
        }
        private function onClientSocketData( event:ProgressEvent):void
        {
            var buffer:ByteArray = new ByteArray();
            _client.readBytes( buffer, 0, _client.bytesAvailable );
            log( "Send: " + buffer.toString() );
        }
        /**
         * 接收到服务器发送的数据
         */
        private function onSocketData(e:ProgressEvent):void
        {
            var buffer:String = _client.readUTFBytes(_client.bytesAvailable );
            var data:String = buffer.split("\n")[0];
            AppEventDispatcher.getInstance().dispatchEvent(new AppEvent(AppEvent.SERVER_DATA,data));
            log( "Received from Server:" + buffer );
        }
        /**
         * 向服务端发送数据
         * @param msg 数据
         */
        private function send(msg:String):void
        {
            try
            {
                if( _client != null && _client.connected )
                {
                    _client.writeUTFBytes(msg);
                    _client.flush(); 
                    //log( "Sent message to " + clientSocket.remoteAddress + ":" + clientSocket.remotePort );
                }
                else log("No socket connection.");
            }
            catch ( error:Error )
            {
                log( error.message );
            }
        }
        private function onError(e:IOErrorEvent):void
        {
            log(e.toString());
        }
        public function log(message:String):void
        {
            //trace(message);
        }

    }
}
class S{};

 

代码中的导入的类:

import com.models.events.AppEvent;
import com.models.events.AppEventDispatcher;

是用于接收到数据后向外派发事件时所用,可自行处理。

 

posted on 2016-08-12 14:05  晏过留痕  阅读(3638)  评论(0编辑  收藏