服务端

package 
{
    import flash.display.Sprite;
    import flash.net.ServerSocket;
    import flash.net.Socket;
    import flash.events.ServerSocketConnectEvent;
    import flash.events.ProgressEvent;
    import flash.events.*;
    import flash.utils.ByteArray;

    public class TCPServer extends Sprite
    {
        var serverSocket:ServerSocket = new ServerSocket();
        var clientSocket:Socket;
         var _clients:Array = [];

        private static var instance:TCPServer;
        public static function Instance():TCPServer
        {
            if (instance==null)
            {
                instance=new TCPServer();
            }
            return instance;
        }

        public function TCPServer()
        {
            // constructor code
        }
        //绑定服务器ip 开始监听端口
        function bindFunc(_ip:String="192.168.1.116",_port:int=8080):void
        {
            if (serverSocket.bound)
            {
                serverSocket.close();
                serverSocket = new ServerSocket();

            }
            // serverSocket.bind( parseInt( localPort.text ), localIP.text );
            serverSocket.bind( _port,_ip );
            serverSocket.addEventListener( ServerSocketConnectEvent.CONNECT, onConnect );
            serverSocket.listen();
            trace( "Bound to: " + serverSocket.localAddress + ":" + serverSocket.localPort );
            // log( "Bound to: " + serverSocket.localAddress + ":" + serverSocket.localPort );
            
            
        }
        //当客户端成功连接服务端
        function onConnect( event:ServerSocketConnectEvent):void
        {
            clientSocket = event.socket;
            clientSocket.addEventListener( ProgressEvent.SOCKET_DATA, onClientSocketData );
            _clients.push(clientSocket);
            trace("Connection from " + clientSocket.remoteAddress + ":" + clientSocket.remotePort );
            trace('连接成功'+"Connection from " + clientSocket.remoteAddress + ":" + clientSocket.remotePort );
            //log( "Connection from " + clientSocket.remoteAddress + ":" + clientSocket.remotePort );
            
            clientSocket.addEventListener(Event.CLOSE,oncccccc);
        }
        //当有数据通信时
        function onClientSocketData( event:ProgressEvent ):void
        {
            var buffer:ByteArray = new ByteArray();
            clientSocket.readBytes( buffer, 0, clientSocket.bytesAvailable );
            //   log( "Received: " + buffer.toString() );
            trace( "Received: " + buffer.toString() );
            trace( '数据'+"Received: " + buffer.toString() );
            if (buffer.toString() == 'zuo')
            {
                trace("zuo-------------");
            }
            if (buffer.toString() == 'you')
            {
                trace("you-------------");
            }
            for (var i:int = 0; i < _clients.length; i++)
            {
                var item:Socket = _clients[i] as Socket;
                if (! item)
                {
                    continue;
                }
                item.writeObject(buffer.toString());
                item.flush();
            }


        }
        //服务器端向所有客户端发送数据
        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.writeObject(message.text);
                    item.writeObject('aaaa');
                    item.flush();
                }

                /*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 );
            }
        }
        function oncccccc(e:Event):void{
            trace("cccccccccccccc");
            var _index:int= this._clients.indexOf(e.currentTarget);
            _clients.splice(_index,1);
            trace(_index);
        }

    }

}

 

客户端

package  {
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.IOErrorEvent;
    import flash.net.ServerSocket;
    import flash.net.Socket;
    import flash.events.ProgressEvent;
    import flash.utils.ByteArray;
    
    public class TCPClient extends Sprite{
        private static var instance:TCPClient;
        public static function Instance():TCPClient
        {
            if (instance==null)
            {
                instance=new TCPClient();
            }
            return instance;
        }
        
        private var _client:Socket ;
        
        private var clientHost:String;
        private var clientPort:int;
        
        /**
         * 开始连接服务器
         * @param host ip地址
         * @param port 端口
         */
        public function collect(host:String="192.168.1.116",port:int=8080):void
        {
            clientHost=host;
            clientPort=port;
            
            log('开始连接服务器!');
            trace(host,port);
            
            _client= new Socket();
            _client.timeout=1000;
            _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 数据
         */
        public function sendFunc(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.");
                if(!_client.connected){
                    _client=null;
                    collect(clientHost,clientPort);
                    _client.writeUTFBytes(msg);
                    _client.flush();
                }
            }
            catch ( error:Error )
            {
                log( error.message );
                
            }
        }
        //向服务端发送HEX数据
        public function sendHEXFunc(msg:ByteArray):void
        {
            try
            {
                if( _client != null && _client.connected )
                {
                    _client.writeBytes(msg);
                    _client.flush(); 
                    //log( "Sent message to " + clientSocket.remoteAddress + ":" + clientSocket.remotePort );
                }
                else log("No socket connection.");
                if(!_client.connected){
                    _client=null;
                    collect(clientHost,clientPort);
                    _client.writeBytes(msg);
                    _client.flush();
                }
            }
            catch ( error:Error )
            {
                log( error.message );
                
            }
        }
        private function onError(e:IOErrorEvent):void
        {
            log(e.toString());
            
            /*_client.removeEventListener(Event.CONNECT, onConnect);//监听连接事件
            _client.removeEventListener(IOErrorEvent.IO_ERROR,onError);
            _client.removeEventListener(ProgressEvent.SOCKET_DATA,onSocketData);*/
            
            _client=null;
            collect(clientHost,clientPort);
        }
        public function log(message:String):void
        {
            trace(message);
        }
    }
    
}

调用方法

var tcpServer:TCPServer=TCPServer.Instance();
        var tcpClient:TCPClient=TCPClient.Instance();
        public function Main() {
            // constructor code
            
            tcpServer.bindFunc();
            
            
            tcpClient.collect();
            
            
            stage.addEventListener(KeyboardEvent.KEY_DOWN,ddddd);
        }
function ddddd(e:KeyboardEvent):void{
            tcpClient.sendFunc(e.keyCode+"");
            
            //aa ff ff 1b 01 cc bf 28
            //aa ff ff 1b 02 cc d7 02
            //AA FF FF 1B 03 CC 0F 1B
            
            tcpClient.sendHEXFunc(tenToHexFunc("aa ff ff 1b 01 cc bf 28"));
            //tcpClient.sendFunc("AA FF FF 1B 03 CC 0F 1B");
            
            
        }
        //将string转为HEX
        function tenToHexFunc(_info:String):ByteArray{
            
            _info=_info.split(" ").join("");//删除所有的空格
            
            var byte:ByteArray = new ByteArray();
                for (var i:uint = 0; i < _info.length; i = i + 2)
                {
                    //trace(i);
                    byte.writeByte(uint("0x" + _info.substr(i, 2)))
                    trace(_info.substr(i, 2));
                }
                //writeBytes(byte)
            
            
            return byte;
        }

 

posted on 2019-02-22 16:42  凌落成迷  阅读(443)  评论(0编辑  收藏  举报