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

以下类是充当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:[email protected]
     * @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:[email protected]
     * @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;
        }        

    }
}
时间: 2024-10-14 02:13:28

[ActionScript 3.0] AS3.0 Socket通信实例的相关文章

java NIO socket 通信实例

java Nio 通信与Bio通信主要不同点: 1.Nio中的单个channel即可支持读操作也可以支持写操作,而bio中读操作要用inputstream,写操作要outputstream. 2.nio 采用byteBuffer 作为内存缓存区,向channel里写或者度操作,bio基本是用byte[] 3.nio采用 selector组件轮询读取就绪channel 服务端demo代码: package com.my.socket3; import java.io.ByteArrayOutput

(8)Linux(客户端)和Windows(服务端)下socket通信实例

Linux(客户端)和Windows(服务端)下socket通信实例: (1)首先是Windows做客户端,Linux做服务端的程序 Windows   Client端 #include <stdio.h> #include <Windows.h> #pragma comment(lib, "ws2_32.lib") #define Port 5000 #define IP_ADDRESS "192.168.1.30"     //服务器地址

Linux下简单的socket通信实例

Linux下简单的socket通信实例 If you spend too much time thinking about a thing, you’ll never get it done. —Bruce Lee       学习网络编程也一段时间了,刚开始看<UNIX网络编程>的时候,觉得这本厚厚的书好难啊!看到后来,发现并没有想象中的那么难.如果你是新手,建议你看到第二部分结束后,开始着手写代码.不写代码肯定是不行的.看100遍也没有敲一遍实现一遍来的清楚.敲完以后,带着问题去看书,你会

网络协议栈学习(一)socket通信实例

网络协议栈学习(一)socket通信实例 该实例摘自<linux网络编程>(宋敬彬,孙海滨等著). 例子分为服务器端和客户端,客户端连接服务器后从标准输入读取输入的字符串,发送给服务器:服务器接收到字符串后,发送给服务器:服务器接收到字符串后统计字符串的长度,然后将该值传给客户端:客户端将接收到的信息打印到标准输出. 一.服务器端代码 #include <stdio.h> #include <stdlib.h> #include <string.h> #in

[ActionScript 3.0] AS3.0和AS2.0的相互通信

AS3和AS2之间的通信,最好的方式可能就是LocalConnection了. AS2向AS3发送数据,即AS2调用AS3的函数: as2.0代码(按钮上写的发送信息代码): on (release) { var param = "this message is from as2"; var caller:LocalConnection = new LocalConnection(); caller.send("AS2 send to AS3","funI

python的socket通信实例

一.socket简介 1. 套接字 套接字是为特定网络协议(例如TCP/IP,ICMP/IP,UDP/IP等)套件对上的网络应用程序提供者提供当前可移植标准的对象. 它们允许程序接受并进行连接,如发送和接受数据.为了建立通信通道,网络通信的每个端点拥有一个套接字对象极为重要. 套接字为BSD UNIX系统核心的一部分,而且他们也被许多其他类似UNIX的操作系统包括Linux所采纳. 许多非BSD UNIX系统(如ms-dos,windows,os/2,mac os及大部分主机环境)都以库形式提供

[ActionScript 3.0] AS3.0 对象在一定范围随机显示不重叠

import flash.geom.Rectangle; import flash.display.MovieClip; import flash.display.Sprite; var arr:Array = []; var dis:Number = 20;//间距 var len:int=15;//对象数量 var bound:Rectangle = new Rectangle(0,0,1000,800);//显示范围 for(var i:int = 0;i<len;i++){ var ob

[ActionScript 3.0] AS3.0 水面波纹效果

import flash.geom.Point; import flash.display.BitmapData; import flash.filters.DisplacementMapFilter; import flash.display.MovieClip; import flash.events.Event; /** * 创建湖面微波效果 */ function createWater(target:MovieClip):void { var count:int = 1; var po

[ActionScript 3.0] AS3.0 模拟套索工具抠图的两种方法

方法之一:遮罩法 package com.fylibs.tools { import flash.display.Bitmap; import flash.display.BitmapData; import flash.display.DisplayObject; import flash.display.Shape; import flash.display.Sprite; import flash.events.MouseEvent; import flash.geom.Matrix; i