关闭

Flex的简单消息转发

标签: flexwebjava
131人阅读 评论(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
查看评论

Flex的简单消息转发--逻辑

继上篇,这篇讲原理。 一,逻辑流程 web工程部署启动后,打开主页加swf,在SocketClient中向外开放了send和connect方法的调用,点击按钮时调用了connect的方法。在SocketConnect这个socket封装类中初始化时定义了动作监听,这个监听会在socket...
  • sf0407
  • sf0407
  • 2017-01-04 10:46
  • 137

【IOS学习】消息转发和它的实际应用

消息转发,适用于把操作给另外一个类来实现
  • mangosnow
  • mangosnow
  • 2014-07-01 13:05
  • 5260

OC-消息转发机制

当正常的消息发送走不通的时候,会走下面的消息转发机制:消息转发机制基本分为三个步骤:1、动态方法解析2、备用接受者3、完整转发新建一个HelloClass的类,定义两个方法:@interface HelloClass : NSObject - (void)hello; + (HelloClass *...
  • ShengQiangLiu
  • ShengQiangLiu
  • 2016-03-12 14:48
  • 1047

Ios的消息转发机制

原文链接:http://www.jianshu.com/p/fa29c920409d 这篇博客的前置知识点是 OC 的消息传递机制,如果你对此还不了解,请先学习之,再来看这篇。这篇博客我尝试用口语的方式像讲述 PPT 一样给大家讲述这个知识点。 我们来思考一个问题,如果对象在收到无法解读的消息时...
  • App_IOS
  • App_IOS
  • 2016-09-02 09:43
  • 607

消息转发(Message Forwarding)

发送消息到不处理该消息的对象会发生错误。然而,在声明错误之前,运行时系统给接收对象第二次机会处理该消息。 转发 如果发送消息到不处理该消息的对象,在声明错误之前,运行时给该对象发送forwardInvocation: 消息,NSInvocation 对象作为唯一参数。NSInvocation 对...
  • iosswift
  • iosswift
  • 2015-01-06 22:12
  • 1510

Myeclipse10 整合 Flex4 开发简单例子

第一步  安装FlashBui4.6  破解方法可以网上找 第二步  Myeclispe10和tomcat jdk自行网上安装 第三步  Myeclipse集成Flex环境      1. 进入到  ...
  • soanl
  • soanl
  • 2013-11-19 13:23
  • 2012

OC学习Runtime之消息传递,消息转发机制

坚持 成长 每日一篇
  • u014410695
  • u014410695
  • 2015-09-22 10:48
  • 2129

Flex 入门例子

 一、flex开发环境搭建。二、程序的开发,部署,运行。下面先来看看第一部分:一、flex开发环境的搭建1.安装包下载   flex sdk:http://www.adobe.com/go/flex3_sdk   flex builder 3:htt...
  • a9529lty
  • a9529lty
  • 2009-11-12 22:59
  • 2194

runtime总结二之消息机制(包括消息转发,消息交换的黑魔法)

runtime的消息机制前面提到过编译器最终会把我们的消息发送转化为函数调用 消息发送 [object sendMassage] 首先编译器会在运行时将上面的例子转化为objc_msgSend(obj,@selector(sendMassage))这个函数,转换的时候除了方法本身的参数之外,还有两...
  • li15809284891
  • li15809284891
  • 2017-01-28 20:46
  • 601

Soket转发消息服务(群聊)

编写群聊服务端代码,稍加改写之前的10086服务端的代码,如下: // // ServiceListener.m #import "ServiceListener.h" #import "GCDAsyncSocket.h" @interface Se...
  • github_26672553
  • github_26672553
  • 2016-02-12 14:43
  • 413
    个人资料
    • 访问:1872次
    • 积分:94
    • 等级:
    • 排名:千里之外
    • 原创:8篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类