flex3 socket+java

首先解决的问题是flex的沙箱问题,由于flex 连接服务器存在此问题总是会连接两次服务,首先贴出as文件

package as3.email
{
	import flash.errors.IOError;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.Socket;
	
	import mx.controls.Alert;
	public class EmailReceiveSocket extends Socket {
	private var receiveHandler:Function;
	private var closedHandler:Function;
    public function EmailReceiveSocket() {
        super();
        configureListeners();
        
    }
	public  function connectServer(host:String,port:int,token:String,connectHandler:Function,receiveHandler:Function,closedHandler:Function):void{
		super.addEventListener(Event.CONNECT, connectHandler);
		
		this.closedHandler=closeHandler;
		this.receiveHandler=receiveHandler;
		if (host && port)  {
            super.connect(host, port);
        }
	}
    private function configureListeners():void {
    	addEventListener(Event.CLOSE, closeHandler);
        addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
        addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
        addEventListener(ProgressEvent.SOCKET_DATA, socketDataHandler);
    }

    public function writeln(str:String):void {
       	str += "\n";
        try {
            super.writeUTF(str);
            super.flush();
        }
        catch(e:IOError) {
           Alert.show(e.message);
        }
    }


    private function readResponse():void {
         while(super.bytesAvailable)
        {
            this.receiveHandler(super.readMultiByte(super.bytesAvailable,"utf8"));
         }
    }

    private function closeHandler(event:Event):void {
        this.closedHandler();
    }
    private function ioErrorHandler(event:IOErrorEvent):void {
         Alert.show("ioErrorHandler: " + event);
    }

    private function securityErrorHandler(event:SecurityErrorEvent):void {
         Alert.show("securityErrorHandler: " + event);
    }

    private function socketDataHandler(event:ProgressEvent):void {
         readResponse();
    }
 }
}

 调用

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init(event)">
	<mx:states>
		<mx:State name="login_success" id="login_success">
			<mx:RemoveChild target="{login}"/>
			<mx:AddChild position="lastChild">
				<mx:Label x="116" y="9" width="682" id="msg"/>
			</mx:AddChild>
			<mx:AddChild position="lastChild">
				<mx:Button x="88" y="8" width="20" height="20" label="连接状态" fillColors="[red, red]"  cornerRadius="30" id="cur_state"/>
			</mx:AddChild>
			<mx:AddChild position="lastChild">
				<mx:DataGrid x="10" y="35" width="710" height="405" id="grid">
					<mx:columns>
						<mx:DataGridColumn headerText="编号" dataField="id" width="50" textAlign="center"/>
						<mx:DataGridColumn headerText="标题" dataField="text"/>
					</mx:columns>
				</mx:DataGrid>
			</mx:AddChild>
			<mx:AddChild position="lastChild">
				<mx:Button x="10" y="8" label="连接服务" click="connect(event)" id="conn"/>
			</mx:AddChild>
			<mx:AddChild position="lastChild">
				<mx:Button x="752" y="418" label="发送" click="send(event)"/>
			</mx:AddChild>
			<mx:AddChild position="lastChild">
				<mx:TextInput x="726" y="366" id="context"/>
			</mx:AddChild>
		</mx:State>
	</mx:states>
<mx:Style source="css/email.css"></mx:Style>
	<mx:Panel width="327" height="238" layout="absolute" titleStyleName="loginPanelTitle" title="邮箱登录" id="login" right="60" verticalCenter="20" styleName="loginPanel">
		<mx:Button x="125.5" y="141" label="login" click="loginAction(event)"/>
		<mx:Button x="194.5" y="140" label="reset"/>
		<mx:ComboBox x="91.5" y="30" editable="false" id="service_select" render="service_select_render(data)" width="180"></mx:ComboBox>
		<mx:TextInput id="username" x="91.5" y="61" width="180" focusIn="clearStyles(event)"/>
		<mx:TextInput id="password" x="91.5" y="91" displayAsPassword="true" width="180" focusIn="clearStyles(event)"/>
		<mx:Text x="27.5" y="33" text="邮箱类型"/>
		<mx:Text x="47.5" y="63" text="账号"/>
		<mx:Text x="47.5" y="93" text="密码"/>
	</mx:Panel>
	<mx:Script>
		<![CDATA[
			import flash.utils.setInterval;
			import as3.email.EmailReceiveSocket;
			import mx.rpc.AsyncToken;
			import mx.rpc.events.ResultEvent;
			import mx.core.UITextField;
			import com.google.maps.Color;
			import com.adobe.serialization.json.JSON;
			import mx.controls.Alert;
			import mx.collections.ArrayCollection;
			import mx.rpc.http.mxml.HTTPService;
			private var httpServer:HTTPService=new HTTPService();
			private  var userconfig:Object;
			private var socket:EmailReceiveSocket=new EmailReceiveSocket();
			private var dataArr:ArrayCollection=new ArrayCollection();
			private var i:int=1;
			private function init(evet):void{
				var flexRequest:URLRequest=new URLRequest("../email/listRemoteService.do");
				var flexload:URLLoader=new URLLoader();
				flexload.load(flexRequest);
				flexload.addEventListener(Event.COMPLETE, function(e:Event):void{
					var result=JSON.decode(e.target.data.toString(),true);
					if(result.success){
						var data:Array=result.data;
						for each(var d:Object in data){
							d.label=d.name;	
						}
						service_select.dataProvider=data;
					}else{
					}
				});
			}
			private function service_select_render(data:Object):String{
				return data.name;
			}
			private function loginAction(e):void{
				if(username.text.length==0){
					username.setStyle("borderColor",Color.RED);
					return;
				}
				if(password.text.length==0){
					password.setStyle("borderColor",Color.RED);
					return;
				}
				httpServer.method="POST";
				httpServer.url="../system/user/login.do";
				var params:Object={};
				params.username=username.text;
				params.password=username.text;
				params.pop3=service_select.selectedItem.pop3;
				params.smtp=service_select.selectedItem.smtp;
				httpServer.addEventListener(ResultEvent.RESULT,loginResult);
				httpServer.send(params);
			}
			private function loginResult(e:ResultEvent):void{
				var rst=JSON.decode(e.result.toString(),true);
				if(rst.success){
					userconfig=rst.data;
					this.currentState="login_success";
				}else{
					Alert.show(rst.result_msg);
				}
			};
			private function clearStyles(event:Event):void{
				event.currentTarget.setStyle("borderColor",Color.GRAY9);
			}
			private function send(e:Event):void{
				var message:ByteArray=new ByteArray();
				message.writeUTFBytes(this.context.text +"\n");
				socket.writeBytes(message);
				socket.flush();
			}
			private function connect(e:Event):void{
				socket.connectServer("192.168.1.254",2567,"",connectHandler,receiveHandler,closedHandler);
			}
			private function receiveHandler(data:Object):void{
				var obj:Object=new Object();
				obj.id=i+"";
				obj.text=data.toString();
				dataArr.addItem(obj);
				i++;
			}
			private function closedHandler():void{
				this.cur_state.setStyle("fillColors",[Color.RED]);
				this.conn.enabled=true;
			}
			private function connectHandler(event:Event):void {
	    		this.conn.enabled=false;
	    		this.cur_state.setStyle("fillColors",[Color.GREEN]);
	    		socket.writeln("hello");
	    		socket.flush();
	    		socket.writeln("hello");
	    		socket.flush();
	    		var message:ByteArray=new ByteArray();
				message.writeUTFBytes("start" +"\n");
				socket.writeBytes(message);
				socket.flush();
				grid.dataProvider=dataArr;
	   		}
		]]>
	</mx:Script>
</mx:Application>

 在java服务端做出如下处理:

package com.lyon.yao.CMessage.email.service.impl;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.HashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lyon.yao.CMessage.email.entry.EmailUser;
import com.lyon.yao.CMessage.email.service.IEMailBasicCongfigService;
import com.lyon.yao.CMessage.email.service.ISocketService;
import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;

/**
 * @author lyon.yao
 * @date Dec 23, 2011
 * @function 邮件socket 服务器  实现 
 */
@Service
public class SocketServiceImpl implements ISocketService, Runnable{
	@Autowired
	private IEMailBasicCongfigService config;
	private ServerSocket serverSocket=null;
	public static HashMap<String,EmailUser> users=new HashMap<String, EmailUser>(0);
	private Thread service=new Thread(this);
	private String xml;   
	public SocketServiceImpl() {
		super();
		xml="<?xml version=\"1.0\"?>" +    
		"<!DOCTYPE cross-domain-policy SYSTEM \"http://www.adobe.com/xml/dtds/cross-domain-policy.dtd\">" +    
		"<cross-domain-policy>" +    
		"<allow-access-from domain=\"*\" to-ports=\"*\" />" +    
		"</cross-domain-policy>";  
		// TODO Auto-generated constructor stub
	}

	public void start() throws Exception {
		// TODO Auto-generated method stub
		try {
			serverSocket=new ServerSocket(config.getServicesConfig().getPort());
			service.start();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void stop() throws Exception {
		// TODO Auto-generated method stub
		service.stop();
	}

	@Override
	protected void finalize() throws Throwable {
		// TODO Auto-generated method stub
		if(!serverSocket.isClosed()){
			serverSocket.close();
		}
		super.finalize();
	}

	public void run() {
		// TODO Auto-generated method stub
		while(true){
			try {
			 Socket socket=	serverSocket.accept();
			 System.out.println("连接成功```````");    
			 BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));   
			 PrintWriter pw=new PrintWriter(socket.getOutputStream());    
			 char[] by=new char[22];    
			 br.read(by,0,22); 
			 String head=new String(by);
			 if(head.equals("<policy-file-request/>")){    
			     pw.write(xml+"\0");    
			     pw.flush(); 
			     pw.close();
			     br.close();
			     socket.close();
			 }else{
				 InnerReaderThread inner=new InnerReaderThread(socket);
				 inner.start();
			 }
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	class InnerWriterThread extends Thread{
		OutputStream out=null;
		Socket socket=null;
		InnerWriterThread(Socket socket){
			this.socket=socket;
			try {
				out=socket.getOutputStream();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		public void run() {
			while(true){
				try {
					if(!socket.isClosed()){
						out.write("你好".getBytes());
						out.flush();
					}else{
						break;
					}
					Thread.currentThread().sleep(10000);
				} catch (SocketException e) {
					// TODO: handle exception
					e.printStackTrace();
					if(!socket.isClosed()){
						try {
							socket.close();
							System.out.println("socket closed");
						} catch (IOException e1) {
							e1.printStackTrace();
						}
					}
					break;
				}catch (InterruptedException e) {
					// TODO: handle exception
					e.printStackTrace();
				}catch(IOException e){
					
				}
			}
			
		}
	}
	class InnerReaderThread extends Thread{
		Socket socket=null;
		InputStream input=null;
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				BufferedReader reader=new BufferedReader(new InputStreamReader(input,"UTF-8"));
				String line=null;
				InnerWriterThread out=new InnerWriterThread(socket);
				out.start();
				while((line=reader.readLine())!=null){
					System.out.println(line);
					if(line.equals("exit")){
						if(!socket.isClosed()){
							socket.close();
						}
					}
				}
			} 
			catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		public InnerReaderThread(Socket socket) {
			super();
			// TODO Auto-generated constructor stub
			this.socket=socket;
			try {
				input=socket.getInputStream();
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		protected void setSocket(Socket socket){
			this.socket=socket;
		}
	}
}

 该类中含有两内部类用来发送和接收数据。

就这么多了,运行如图



flex3 socket+java_第1张图片

 

你可能感兴趣的:(socket)