关闭

Flex的简单消息转发

标签: flexwebjava
74人阅读 评论(0) 收藏 举报
分类:

继之前完成了C++加载jvm运行java程序并输出日志之后,接下来需要完成一份工作就是建立一个web应用通过flex来和java程序进行交互。


一,安装flashbuild4.7,使用试用版就行,因为生成后从swf并不需要经常进行改动,仅仅作为收发消息的桥梁。

二,创建一个ActionScript项目,新建一个SokectClient类和一个SocketConnect工具类

SocketClient.as

package
{
	import flash.display.Sprite;
	import flash.external.ExternalInterface;
	import flash.system.Security;
	
	public class SocketClient extends Sprite
	{
		//声明基本属性
		private var serverURL:String = null;
		private var portNumber:int = 0;
		private var connected:Boolean = false;
		private var socketCon:SocketConnect;
		
		public function SocketClient()
		{
			trace("init");
			//此flash允许其他flash 检查和修改 此flash 中的变量、对象、属性、方法
			Security.allowDomain("*");
			//向外公开调用方法
			ExternalInterface.addCallback("send", send);
			ExternalInterface.addCallback("connect", connect);
			trace("hello world");
		}
		
		/**
		 * socket发送信息
		 */
		public function send(msg:String, checkSocket:Boolean = false):void
		{
			socketCon.send(msg, checkSocket);
			trace("send");
		}
		
		/**
		 * 创建链接,默认超时时间为10秒
		 */
		public function connect(serverAddress:String, port:int, timeout:int = 10000):void
		{
			serverURL = serverAddress;
			portNumber = port;
			//关闭之前的链接,重置
			if(socketCon)
			{
				socketCon.close();
			}
			
			//初始化链接
			socketCon = new SocketConnect(serverURL, portNumber, timeout);
			socketCon.toConnect = toConnect;
			socketCon.toSendMsg = toSendMsg;
			socketCon.toSendErr = toSendErr;
		}
		
		/**
		 * 链接
		 */
		public function toConnect(port:int):void
		{
			if(port > 0)
			{
				connected = true;
			}
			//调用JS方法并传入参数
			ExternalInterface.call("toConnect", port)
		}
		
		/**
		 * 发送消息
		 */
		public function toSendMsg(msg:String):void
		{
			//调用JS方法并传入参数
			ExternalInterface.call("toSendMsg", msg)
		}
		
		/**
		 * 发生错误信息
		 */
		public function toSendErr(msg):void
		{
			//调用JS方法并传入参数
			ExternalInterface.call("toSendErr", msg.toString())
		}
		
	}
}
SocketConnect.as

package
{
	import flash.events.DataEvent;
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.XMLSocket;
	import flash.system.Security;

	public class SocketConnect
	{
		//声明服务端地址,端口,socket对象,状态
		private var serverURL:String = null;
		private var portNumber:int = 0;
		private var socket:XMLSocket;
		private var state:int = 0;
		
		//声明发送消息的动作
		public var toConnect:Function;
		public var toSendMsg:Function;
		public var toSendErr:Function;
		
		
		/**
		 * 创建链接,默认超时时间为10秒
		 */
		public function SocketConnect(serverAddress:String, port:int, timeout:int = 10000)
		{
			//设置地址和端口
			serverURL = serverAddress;
			portNumber = port;
			
			Security.allowDomain("*");
			try
			{
				//重置socket内容
				socket = null;
				socket = new XMLSocket();
				if(timeout > 0){
					socket.timeout = timeout;
				}
				
				//添加事件监听
				socket.addEventListener(Event.CLOSE, closeHandler);
				socket.addEventListener(Event.CONNECT, connectHandler);
				socket.addEventListener(DataEvent.DATA, dataHandler);
				socket.addEventListener(ErrorEvent.ERROR, errorHandler);
				socket.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
				socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
				socket.addEventListener(ProgressEvent.SOCKET_DATA, progressdataHandler);
				
				//创建链接
				socket.connect(serverURL, portNumber);
			} 
			catch(error:Error) 
			{
				
			}
			
		}
		
		/**
		 * 链接事件
		 */
		private function connectHandler(evnet:Event):void
		{
			//当socket链接成功时,发送链接消息
			if(socket.connected)
			{
				toConnect(portNumber);
			}
			else
			{
				toConnect(0);
			}
			trace("connect");
		}
		
		/**
		 * 关闭事件
		 */
		private function closeHandler(event:Event):void
		{
			trace("close");
		}
		
		/**
		 * 错误事件
		 */
		private function errorHandler(event:ErrorEvent):void
		{
			toSendErr(event);
		}
		
		/**
		 * IO错误事件
		 */
		private function ioErrorHandler(event:IOErrorEvent):void
		{
			toSendErr(event);
		}
		
		/**
		 * 安全错误事件
		 */
		private function securityErrorHandler(event:SecurityErrorEvent):void
		{
			toSendErr(event);
		}
		
		/**
		 * 数据事件
		 */
		private function dataHandler(event:DataEvent):void
		{
			toSendMsg(event.data)
			trace("data");
		}
		
		
		/**
		 * 数据事件
		 */
		private function progressdataHandler(event:ProgressEvent):void
		{
			//toSendMsg(event.toString())
			trace("progressdataHandler:" + event.bytesLoaded + " total:" + event.bytesTotal);
		}
		
		/**
		 * 关闭sock
		 */
		public function close():void
		{
			try
			{
				if(socket)
				{
					//移除事件监听
					socket.removeEventListener(Event.CLOSE, closeHandler);
					socket.removeEventListener(Event.CONNECT, connectHandler);
					socket.removeEventListener(ErrorEvent.ERROR, errorHandler);
					socket.removeEventListener(DataEvent.DATA, dataHandler);
					socket.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
					socket.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
					socket.removeEventListener(ProgressEvent.SOCKET_DATA, progressdataHandler);
					//断开
					if(socket.connected)
					{
						socket.close();
					}
				}
			} 
			catch(error:Error) 
			{
				
			}
		}
		
		/**
		 * 发送消息,默认不校验socket状态
		 */
		public function send(msg:String, checkSocket:Boolean = false):void
		{
			try
			{
				if(checkSocket)
				{
					//socket不为空且已连接
					if(socket && socket.connected)
					{
						socket.send(msg);
					}
				}
				else
				{
					socket.send(msg);
				}
			} 
			catch(error:Error) 
			{
				
			}
		}
	}
}
三,编译通过后会生成如下文件


获取bin-debug目录下的4个文件。

五,打开eclipse新建一个Dynamic java project,将上面获取的4个文件放入到WebContent目录下,重命名SokectClient.html为index.jsp,并作如下改造:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
    <style type="text/css" media="screen"> 
        html, body  { height:100%; }
        body { margin:0; padding:0; overflow:auto; text-align:center; 
               background-color: #ffffff; }   
        object:focus { outline:none; }
        #flashContent { display:none; }
    </style>
    
    <!-- Enable Browser History by replacing useBrowserHistory tokens with two hyphens -->
    <!-- BEGIN Browser History required section -->
    <link rel="stylesheet" type="text/css" href="history/history.css" />
    <script type="text/javascript" src="history/history.js"></script>
    <!-- END Browser History required section -->  
        
    <script type="text/javascript" src="swfobject.js"></script>
    <script type="text/javascript">
        // For version detection, set to min. required Flash Player version, or 0 (or 0.0.0), for no version detection. 
        var swfVersionStr = "11.4.0";
        // To use express install, set to playerProductInstall.swf, otherwise the empty string. 
        var xiSwfUrlStr = "playerProductInstall.swf";
        var flashvars = {};
        var params = {};
        params.quality = "high";
        params.bgcolor = "#ffffff";
        params.allowscriptaccess = "sameDomain";
        params.allowfullscreen = "true";
        var attributes = {};
        attributes.id = "SocketClient";
        attributes.name = "SocketClient";
        attributes.align = "middle";
        var isInternetExplorer = swfobject.ua.ie;
        swfobject.embedSWF(
            "SocketClient.swf", "flashContent", 
            "100%", "100%", 
            swfVersionStr, xiSwfUrlStr, 
            flashvars, params, attributes);
        // JavaScript enabled so display the flashContent div in case it is not replaced with a swf object.
        swfobject.createCSS("#flashContent", "display:block;text-align:left;");
    </script>
	<script type="text/javascript">
		var socketClient;
		function startClient(){
			//alert("connect start");
			connect("127.0.0.1",1234);
			//alert("connect");
			send("abcde");
			//alert("send");
		}
		
		function resetSocketClient(){
			socketClient = (isInternetExplorer)?window.SocketClient:window.document.SocketClient;
		}
		
		function connect(serverAddress, port){
			resetSocketClient();
			socketClient.connect(serverAddress, port);
		}
		
		function send(msg){
			resetSocketClient();
			socketClient.send(msg);
		}
		
		function toConnect(port){
			alert("toConnect" + port);
			socketClient.send("hahahaha");
		}
	
	</script>
</head>
<body>
	</br></br></br></br></br></br>
	<div align="center">
		<button type="button" style="font-size: 24px; text-align: center; width: 230px; height: 45px; padding-bottom: 0px:margin;0px;"
			class="button" onclick="javascript:startClient();">
			client
		</button>
	</div>
	
	
    <!-- SWFObject's dynamic embed method replaces this alternative HTML content with Flash content when enough 
         JavaScript and Flash plug-in support is available. The div is initially hidden so that it doesn't show
         when JavaScript is disabled.
    -->
    <div id="flashContent">
        <p>
            To view this page ensure that Adobe Flash Player version 
            11.4.0 or greater is installed. 
        </p>
        <script type="text/javascript"> 
            var pageHost = ((document.location.protocol == "https:") ? "https://" : "http://"); 
            document.write("<a href='http://www.adobe.com/go/getflashplayer'><img src='" 
                            + pageHost + "www.adobe.com/images/shared/download_buttons/get_flash_player.gif' alt='Get Adobe Flash player' /></a>" ); 
        </script> 
    </div>
    
    <noscript>
        <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100%" height="100%" id="SocketClient">
            <param name="movie" value="SocketClient.swf" />
            <param name="quality" value="high" />
            <param name="bgcolor" value="#ffffff" />
            <param name="allowScriptAccess" value="always" />
            <param name="allowFullScreen" value="true" />
            <!--[if !IE]>-->
            <object type="application/x-shockwave-flash" data="SocketClient.swf" width="100%" height="100%">
                <param name="quality" value="high" />
                <param name="bgcolor" value="#ffffff" />
                <param name="allowScriptAccess" value="always" />
                <param name="allowFullScreen" value="true" />
            <!--<![endif]-->
            <!--[if gte IE 6]>-->
                <p> 
                    Either scripts and active content are not permitted to run or Adobe Flash Player version
                    11.4.0 or greater is not installed.
                </p>
            <!--<![endif]-->
                <a href="http://www.adobe.com/go/getflashplayer">
                    <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash Player" />
                </a>
            <!--[if !IE]>-->
            </object>
            <!--<![endif]-->
        </object>
    </noscript>     
</body>
</html>
六,新建一个java工程,新建2个Socket服务端类
package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerService{
	private int serverPort = 1234;
	private ServerSocket serverSocket = null;
	
	BufferedReader bfReader = null;
	String msg = "";
//	PrintStream out = null;
	
	
	public ServerService(){
	}
	
	public void startService() throws IOException{
		serverSocket = new ServerSocket(serverPort, 3, InetAddress.getByName("localhost"));
		while(true){
			Socket socket = null;
			socket = serverSocket.accept();
			System.out.println("get connect" + socket.getInetAddress() + socket.getPort());
			
			//获取输入的流
			InputStream inputStream = socket.getInputStream();
			socket.setKeepAlive(true);
			bfReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			msg = readLine();
			if(msg == null || msg.length() <= 0){
				continue;
			}
			System.out.println(msg);
			if(socket != null){
				socket.close();
			}
		}
	}
	
	private String readLine() throws IOException {
		StringBuilder sb = new StringBuilder();
		int readcode = 0;
		while((readcode = bfReader.read()) != -1){
			if(readcode != '\0' && readcode != '\n' && readcode != '\r'){
				sb.append((char)readcode);
			}
			else{
				//System.out.println((int)readcode);
				break;
			}
		}
		String msg = sb.toString();
		return msg;
	}
	
	
	
	
	public static void main(String[] args) {
		ServerService ss = new ServerService();
		try {
			ss.startService();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
package test;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class CrossDomainService{
	private int serverPort = 843;
	private ServerSocket serverSocket = null;
	
	BufferedReader bfReader = null;
	String msg = "";
	String policy = "<cross-domain-policy><allow-access-from domain=\"*\" to-ports=\"*\" /></cross-domain-policy>";
	
	
	public CrossDomainService(){
	}
	
	public void startService() throws IOException{
		serverSocket = new ServerSocket(serverPort, 3, InetAddress.getByName("localhost"));
		while(true){
			Socket socket = null;
			socket = serverSocket.accept();
			System.out.println("get connect" + socket.getInetAddress() + socket.getPort());
			
			//获取输入的流
			InputStream inputStream = socket.getInputStream();
			socket.setKeepAlive(true);
			bfReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			msg = readLine();
			if(msg == null || msg.length() <= 0){
				continue;
			}
			System.out.println(msg);
			OutputStream outputStream = socket.getOutputStream();
			outputStream.write(policy.getBytes());
			outputStream.flush();
//			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
//			bw.write(policy.toCharArray(),0,policy.length());
//			bw.flush();
			
			System.out.println("send policy");
			
			if(socket != null){
				socket.close();
			}
		}
	}
	
	private String readLine() throws IOException {
		StringBuilder sb = new StringBuilder();
		int readcode = 0;
		while((readcode = bfReader.read()) != -1){
			if(readcode != '\0' && readcode != '\n' && readcode != '\r'){
				sb.append((char)readcode);
			}
			else{
				//System.out.println((int)readcode);
				break;
			}
		}
		String msg = sb.toString();
		return msg;
	}
	
	
	
	
	public static void main(String[] args) {
		CrossDomainService ss = new CrossDomainService();
		try {
			ss.startService();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
七,将web应用部署到tomcat上并启动,启动2个socket监听,访问部署的应用,点击出现的按钮, 如果弹出

toConnect1234
说明:浏览器---->>flex---->>java---->>flex---->>浏览器,消息联通了。

查看2个socket的输出可以看到

          

下一篇简单解释一下原理


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1175次
    • 积分:70
    • 等级:
    • 排名:千里之外
    • 原创:6篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档