flashxmlsocket:FLEX IO 的XMLSocket来源: 发布时间:星期四, 2009年2月12日 浏览:97次 评论:0
门好语言需要良好支持IO操作, Java有了Socket才有了JDBC, Servlet, Tomcat and etc. 先看下FLEXXMLSocket. XMLSocket提供接口比较简单, 文档还有简单例子, 跟Java区别写法比较大就是它异步回调. FLASH客户端代码: 门好语言需要良好支持IO操作, Java有了Socket才有了JDBC, Servlet, Tomcat and etc. 先看下FLEXXMLSocket. XMLSocket提供接口比较简单, 文档还有简单例子, 跟Java区别写法比较大就是它异步回调. <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="800" height="600" creationComplete="initApp"> <mx:Script><![CDATA[ import mx.controls.Alert; private var sock:XMLSocket = null; //Initial the GUI private function initApp:void { } //Click logon private function connectServer(event:MouseEvent):void { (this.sock != null) ; this.sock = XMLSocket; //Refer to XMLSocket document, follow the sample here this.configureListeners(this.sock); this.sock.connect("localhost", 8080); this.sendButton.enabled = true; } public function send(data:Object):void { this.sock.send(data); } private function configureListeners(dispatcher:IEventDispatcher):void { dispatcher.addEventListener(Event.CLOSE, closeHandler); dispatcher.addEventListener(Event.CONNECT, connectHandler); dispatcher.addEventListener(DataEvent.DATA, dataHandler); dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler); dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); } private function closeHandler(event:Event):void { trace("closeHandler: " + event); this.appendLine("CLose event "); } private function connectHandler(event:Event):void { trace("connectHandler: " + event); this.appendLine("Send: connect to server sucessfully." + event.target.toLocaleString); } private function appendLine(mesg:String):void { //The \0 will be added automatically like C this.messageArea.text (mesg); } private function dataHandler(event:DataEvent):void { trace("dataHandler: " + event); this.appendLine("Server Response:" + event.data); //this.messageArea.text ("Server Response:" + event.target.toLocaleString + "\r\n"); } private function ioErrorHandler(event:IOErrorEvent):void { trace("ioErrorHandler: " + event); this.appendLine("Oops, ioError"); } private function progressHandler(event:ProgressEvent):void { trace("progressHandler loaded:" + event.sLoaded + " total: " + event.sTotal); } private function securityErrorHandler(event:SecurityErrorEvent):void { trace("securityErrorHandler: " + event); this.appendLine("Oops, encounter security error:" + event.text); } private function sendMessage(event:MouseEvent):void { var message:String = this.messageField.text; //message = "<message>" + message + "</message>\r\n"; message = message + "\r\n"; (message != null && message.length > 0) { this.send(message); //this.messageArea.text ("Send:" + message + "\r\n"); this.appendLine("Send:" + message ); } } ]]> </mx:Script> <mx:TextArea x="10" y="10" width="780" height="386" id="messageArea"/> <mx:TextInput x="10" y="416" width="536" height="31" id="messageField"/> <mx:Button x="577" y="416" label="Send" height="31" width="69" id="sendButton" enabled="false" click="sendMessage(event)"/> <mx:Button x="669" y="416" label="Logon" height="31" id="logonButton" click="connectServer(event)"/> </mx:Application> JAVA服务器: /* * testflex.CellPhoneLocator.java 2008-12-23 */ package testflex; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrWriter; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; /** * The demo provided to test the flash XMLSocket * @author zealvampire * @version 1.0 2008-12-23 */ public CellPhoneLocator { /** The listening port of server. */ private serverPort = 8080; private backlog = 50; private InetAddress bindAddress = null; private Map<String,String> questions = HashMap<String,String>(5); private boolean toStopServer = false; //Open 843 to handle the policy request. private PolicyService policyService = null; /** The server */ private ServerSocket serverSocket = null; public CellPhoneLocator { questions.put("130", "130's from chinaunicom"); questions.put("131", "131's from chinaunicom"); questions.put("133", "133's from Chinatelecom"); questions.put("135", "135's from China Mobile"); questions.put("138", "138's from China Mobile"); } private String locateNumber(String phoneNum) { String location = this.questions.get(phoneNum); locationnull ? (phoneNum + "'s Unknown") : location; } private FlexStringReader extends InputStreamReader { private StringBuffer buf = StringBuffer; public FlexStringReader(InputStream in) { super(in); } public FlexStringReader(InputStream in, String charName) throws UnsupportedEncodingException { super(in, charName); } //Make sure it works. public String readLine throws IOException { _disibledevent=>buf.Length(0); while ((oneChar = this.read) != -1) { (oneChar '\0') ; buf.append((char) _disibledevent=>public RequestHanlder(Socket pSock) { this.sock = pSock; } private String command = ""; private String parameter = ""; public void run { FlexStringReader reader = null; PrWriter pw = null; String line = null; try { .out.prln("Client:" + this.sock); InputStream in = this.sock.getInputStream; reader = FlexStringReader(in, "UTF-8"); pw = PrWriter(this.sock.getOutputStream); String policyRequest = reader.readLine;// String(headers); //FLash client will open two ports, _disibledevent=>pw.flush; .out.prln("Policy's sent by current listening port:" + serverPort); Thread.sleep(10000); throw IOException("A dirty , never follow it dude."); } { pw.write("Hi " + this.sock + ",at your service, send me the cell phone please.\0"); } pw.flush; while ((line = reader.readLine).length > 0) { this.parseRequest(line); ("where".equalsIgnoreCase(command)) { pw.write(locateNumber(this.parameter)+ '\0'); pw.flush; } ("quit".equalsIgnoreCase(command) || "exit".equalsIgnoreCase(command)) { ; } { pw.write("Oops, unknown command.\0"); pw.flush; } } } catch (IOException e) { e.prStackTrace; } catch (InterruptedException e) { e.prStackTrace; } finally { //FIXME, try to close the I/O stream try { sock.close; } catch (IOException e) { e.prStackTrace; } } } private void parseRequest(String line) { command = ""; parameter = ""; StringTokenizer tokens = StringTokenizer(line, " \t\n\r\f\0", false); count = tokens.countTokens; (count > 0) { this.command = tokens.nextToken; (count > 1) this.parameter = tokens.nextToken; } .out.prln("Command=" + this.command + "\tParameter=" + this.parameter); } } /** * Start the server first. * @throws IOException */ public void startServer throws IOException { this.serverSocket = ServerSocket(serverPort, backlog, bindAddress); .out.prln( Date + ": Starting server."); //The policy swith this.policyService = PolicyService; this.policyService.start; } private PolicyService extends Thread { private ServerSocket policySock = null; public void run { try { this.policySock = ServerSocket(843); .out.prln( Date + ":The policy server is running _disibledevent=>String request = null; FlexStringReader br = null; PrWriter pw = null; //FIXME, create another thread to handle the request. while ((sock = this.policySock.accept) != null) { br = FlexStringReader(sock.getInputStream); pw = PrWriter(sock.getOutputStream); .out.prln("Policy server:client =" + sock); request = br.readLine; .out.prln("Policy service: request=" + request); (request.startsWith("<policy-file-request/>")) { pw.write("<?xml version=\"1.0\"?><cross-do-policy><site-control permitted-cross-do-policies=\"all\"/><allow-access-from do=\"*\" to-ports=\"*\" /></cross-do-policy>\0"); pw.flush; .out.prln("Policy service:Policy file's sent......"); //Wait until the xml's pushed to client. Thread.sleep(10000); } //FIXME, not a good way the release resources. .out.prln("Policy service: close the client ."); br.close; pw.close; sock.close; } } catch (IOException e) { e.prStackTrace; } catch (InterruptedException e) { e.prStackTrace; } finally { //FIXME, refactor it .. (this.policySock != null) { try { this.policySock.close; } catch (IOException e) { e.prStackTrace; } } } } } /** * Service's running * @throws IOException */ public void service throws IOException { Socket clientSock = null; Thread handler = null; while (!this.toStopServer && (clientSock = this.serverSocket.accept) != null) { //FIXME, _disibledevent=>handler.start; } this.releaseResource; } public void releaseResource { (this.serverSocket != null) try { this.serverSocket.close; this.serverSocket = null; } catch (IOException e) { // TODO Auto-generated catch block e.prStackTrace; } } /** * @param args */ public void (String args) { CellPhoneLocator server = CellPhoneLocator; try { server.startServer; server.service; } catch (IOException e) { e.prStackTrace; server.releaseResource; } } /** * @ the serverPort */ public getServerPort { serverPort; } /** * @param serverPort the serverPort to */ public void ServerPort( serverPort) { this.serverPort = serverPort; } } 麻烦只是权限, flash player只相信个原则, SWF从哪里来, 它就相信哪个域; 也就是说SWF本地运行还有从网络下载到浏览器它采访权限是完全不样, SANDBOX沙漏这个限制就好像java applet样. 我们需要设置好policy. 1. 在本地Flash player运行, I mean 直接点击生成SWF 不需要设置, XMLSocket可以直接发送接受服务器信息. 不过我这里用都是localhost, 不知道使用外部IP会如何..不确定. 2. SWF放在web 服务器下, 使用浏览器采访 (1)默认先连XMLSocket目标服务器843端口, 发送<policy-file-request/>\0 类似这样信息. 我们返回"<?xml version=\"1.0\"?><cross-do-policy><site-control permitted-cross-do-policies=\"all\"/><allow-access-from do=\"*\" to-ports=\"*\" /></cross-do-policy>\0" (2) 如1失败, 则查看AS中是否 Security.loadPolicyFile( "xml://host:port" ) 有则尝试加载crossdo.xml (3)2失败则只能链XMLSocket目标端口了. 还失败就不可能建立连接了. 3.需要注意是XMLSocket未必定要发送XML, 你也可以直接发送String, 但是flex里面发送过去是以\0结束. 后台需要额外处理下\0; 返回到flash串也必须使用\0才能在在客户端接收到. 冇办法, 每个语言都有自己规则. private function dataHandler(event:DataEvent):void { trace("dataHandler: " + event); this.appendLine("Server Response:" + event.data); //this.messageArea.text ("Server Response:" + event.target.toLocaleString + "\r\n"); } 的后会继续测试下Flex binary 和其他IO 0
相关文章
读者评论发表评论 |