`

利用AIR的ServerSocket类让 AIR 做socket服务器

    博客分类:
  • flex
 
阅读更多

新的air sdk 新增了 ServerSocket类, 利用它我们做一些简单的局域网应用,比如小型的办公聊天软件,以及一些基于socket的服务应用.这样as程序员可以自己搞定服务器端,不在去求于java程序员.在一下大型应用还没有尝试过.期待有人能做一下大型应用的尝试.小型的办公应用足够能满足了.

首先看服务器端代码:

?View Code ACTIONSCRIPT
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;
 
    public class Main 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 Main()
        {
            setupUI();
        }
 
        //当客户端成功连接服务端
        private function onConnect( event:ServerSocketConnectEvent):void
        {
            clientSocket = event.socket;
            clientSocket.addEventListener( ProgressEvent.SOCKET_DATA, onClientSocketData );
	   _clients.push(clientSocket);
            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( "Received: " + buffer.toString() );
 
			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();
			}
 
 
        }
        //绑定服务器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.writeObject(message.text);
					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 );
            }
        }
 
	// 输出日志
        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", "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;
        }        
    }
}

客户端代码,主要就是连接服务器端:

?View Code ACTIONSCRIPT
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;
 
    public class MainClient 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 MainClient()
        {
            setupUI();
        }
 
        private function onConnect( event:Event ):void
        {
            log('成功连接服务器!');
			//trace('成功连接服务器!!!!');
            //clientSocket.addEventListener( ProgressEvent.SOCKET_DATA, onClientSocketData );
            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( "Received: " + buffer.toString() );
        }
 
		public function bind(host:String = "localhost", port:Number = 9080):void
           {
			log('开始连接服务器!');
			clientSocket = new Socket( localIP.text, parseInt( localPort.text ));
			clientSocket.addEventListener(Event.CONNECT, onConnect);//监听连接事件
 
		}
 
	//向服务器发送数据
        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 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");
			localIP.text = 'localhost';
            localPort = createTextField( 10, 35, "Local port", "0" );
            createTextButton( 170, 60, "Bind", bind );
            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;
        }        
    }
}

整体实现起来比较简单, 服务器端可以做分发. 如果做个聊天室也非常容易. 期待air的效率能再提高一些.

分享到:
评论

相关推荐

    as3 Air ServerSocket

    本文将详细介绍如何利用 AS3 和 Adobe AIR 的 `ServerSocket` 类来实现一个支持 WebSocket 协议的服务端应用。此示例代码片段展示了基本的设置步骤,并提供了关于如何处理客户端连接以及如何解析 WebSocket 握手请求...

    全AIR 的 Socket通信(air服务端、air客户端)

    在AIR中,我们可以使用AS3的Socket类来创建和管理Socket连接。这个类提供了打开、读取、写入和关闭Socket连接的方法。 在建立AIR服务端时,我们需要创建一个监听特定端口的Socket服务器。首先,实例化一个Socket...

    Socket+ServerSocket代码

    Socket和ServerSocket是Java编程语言中的两个核心网络通信类,它们在实现客户端-服务器应用程序时起着关键作用。本文将深入探讨这两个类的功能、用法以及如何在实际项目中使用它们。 首先,让我们理解ServerSocket...

    AIR迷你web服务器

    1. ServerSocket类的使用:在AIR中,ServerSocket类用于创建TCP/IP服务器端套接字,它可以监听特定的端口,等待客户端连接。一旦有客户端连接,就会触发ServerSocketConnectEvent事件,开发者可以在事件处理器中处理...

    airplay java客户端

    2. **网络编程**:Java的`java.net`和`java.nio`包提供了用于网络通信的类和接口,例如Socket和ServerSocket,以及非阻塞I/O的Selector。AirPlay客户端需要建立到服务器的连接,发送请求并接收响应。 3. **多媒体...

    socket及flex饼图,柱状图,面积图实例

    在Java中,我们可以使用Java套接字(java.net.Socket和ServerSocket)类来实现客户端-服务器架构。服务器端创建一个ServerSocket监听特定端口,等待客户端的连接请求。一旦客户端通过Socket连接到服务器,双方就可以...

    java+flex基于socket的聊天案例

    在这个“java+flex基于socket的聊天案例”中,我们将深入探讨如何利用Java作为服务器端技术,Flex作为客户端展示层,通过Socket通信实现一个简单的聊天应用程序。 Java在后台处理业务逻辑和网络通信,它提供了...

    flex socket解决安全沙漏

    例如,可以使用Java的`ServerSocket`和`Socket`类来创建服务器端的监听和响应。 综上所述,解决Flex Socket中的安全沙漏问题涉及到服务器和客户端两方面的配置。理解并正确应用跨域策略是关键,同时,熟悉Flex的...

    flex和java交互 scoket

    在Flex和Java之间进行Socket交互,主要是利用Flex的Socket类和Java的Socket API来实现双向通信。这种通信模式允许客户端和服务器端实时交换数据,适用于实时性要求较高的应用,如在线游戏、聊天室、股票交易系统等。...

    flex与java采用socket方式通信

    - Java服务器端在接收到连接请求后,可以从ServerSocket的`accept()`方法返回的Socket对象上读取数据。 3. **数据接收**: - Java服务器在接收到数据后,可以使用Socket的`InputStream`来读取。通常会用`readUTF...

    yuetai_vip_release.zip yinyuetai.com vip

    依次展示如何使用 Flex Air 的 ServerSocket 和 Socket 实现简化版本的 HTTP 服务器,以及如何加载外部的 SWF 文件并进行操作。 在 mplayer.swf 内部,使用 FlasCC 集成 C 代码做保护。使用了 Hessian 做对象序列化...

    实验二实验报告2

    6. **Socket通信**:在网络编程中,Socket是两个通信端点之间的连接,Java的Socket类和ServerSocket类用于实现客户端-服务器间的通信。 7. **IDEA Ultimate**:这是一个强大的Java集成开发环境,支持自动编码、调试...

Global site tag (gtag.js) - Google Analytics