flex通信篇——socket

相关文章:
http://blog.163.com/terry_boss/blog/static/3335226220088233505852/
http://space.flash8.net/bbs/thread-370600-1-1.html

flex代码:

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
      xmlns:s="library://ns.adobe.com/flex/spark"
      xmlns:mx="library://ns.adobe.com/flex/mx"
      minWidth="955" minHeight="600"
      creationComplete="application1_creationCompleteHandler(event)">
 <fx:Declarations>
  <!-- 将非可视元素(例如服务、值对象)放在此处 -->
 </fx:Declarations>
 <fx:Script>
  <![CDATA[
   import flash.net.Socket;
   
   import mx.events.FlexEvent;
   private var socket1:Socket;
   
   protected function application1_creationCompleteHandler(event:FlexEvent):void
   {
    init();
   }
   
   private function init():void
   {
    socket1 = new Socket();
    socket1.addEventListener(Event.CONNECT,onConnect);
    socket1.addEventListener(ProgressEvent.SOCKET_DATA,onSocketData);
    socket1.addEventListener(IOErrorEvent.IO_ERROR,onIoError);
    socket1.addEventListener(Event.CLOSE,onClose);
    //Security.loadPolicyFile("xmlsocket://127.0.0.1:2234");
    socket1.connect("127.0.0.1",2234);
   }
   
   private function onClick():void
   {
    if(socket1.connected)sendDataFunc();
   }
   
   private function sendDataFunc():void
   {
    var message:ByteArray=new ByteArray();
    message.writeUTFBytes(input.text+"\n");
    socket1.writeBytes(message);
    socket1.flush();
    trace("写入数据成功");
   }
   
   private function onConnect(event:Event):void
   {
    trace("客户端连接服务器成功");
   }
   
   private function onClose(event:Event):void
   {
    trace("连接已断开");
    input.enabled = false;
    sendData.enabled = false;
   }
   
   
   private function onIoError(event:IOErrorEvent):void
   {
    trace("连接错误");
   }
   
   private function onSocketData(event:ProgressEvent):void
   {
    while(socket1.bytesAvailable)
    {
     ouput.text += socket1.readMultiByte(socket1.bytesAvailable,"UTF-8");
    }
   }
   
  ]]>
 </fx:Script>
 <s:TextInput x="126" y="53" width="321" color="#6209F7" id="input"/>
 <s:Label x="39" y="58" text="请输入发送内容" color="#F60E0E"/>
 <s:Button x="455" y="54" label="发送" id="sendData" click="onClick()"/>
 <s:TextArea x="126" y="98" width="321" height="342" id="ouput"/>
 <s:Label x="35" y="99" text="服务器返回数据"/>
</s:Application>


服务器java代码:

package cn.jiabeis.socket;

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

线程类实现socked安全认证:
/**
 * 类实现了java 安全沙认证   http://space.flash8.net/bbs/thread-370600-1-1.html
 * @author Administrator
 *
 */
public class SecurityXMLServer implements Runnable {

 private ServerSocket server;
 private BufferedReader reader;
 private BufferedWriter writer;
 private String xml;

 // http://blog.163.com/terry_boss/blog/static/3335226220088233505852/
 public SecurityXMLServer() {
  String path = "policyfile文件路径";
  // 此处的换成相应的读取xml文档的方式如dom或sax
  // xml = readFile(path, "UTF-8");
  /**
   * 注意此处xml文件的内容,为纯字符串,没有xml文档的版本号
   */
   //String str="<?xml version=\"1.0\" ?>"+"\r\n"; 
         //str+="<!DOCTYPE cross-domain-policy SYSTEM \"http://www.adobe.com/xml/dtds/cross-domain-policy.dtd\">\r\n";
  xml = "<cross-domain-policy>\r\n"
    +"<site-control permitted-cross-domain-policies=\"master-only\"/>\r\n"
    + "<allow-access-from domain=\"*\" to-ports=\"1000-9999\"/>\r\n"
    + "</cross-domain-policy>";
  System.out.println("policyfile文件路径: " + path);
  System.out.println(xml);

  // 启动843端口
  createServerSocket(843);
  new Thread(this).start();
 }

 // 启动服务器
 private void createServerSocket(int port) {
  try {
   server = new ServerSocket(port);
   System.out.println("服务监听端口:" + port);
  } catch (IOException e) {
   System.exit(1);
  }
 }

 // 启动服务器线程
 public void run() {
  while (true) {
   Socket client = null;
   try {
    // 接收客户端的连接
    client = server.accept();

    InputStreamReader input = new InputStreamReader(
      client.getInputStream(), "UTF-8");
    reader = new BufferedReader(input);
    OutputStreamWriter output = new OutputStreamWriter(
      client.getOutputStream(), "UTF-8");
    writer = new BufferedWriter(output);

    // 读取客户端发送的数据
    StringBuilder data = new StringBuilder();
    int c = 0;
    while ((c = reader.read()) != -1) {
     if (c != '\0')
      data.append((char) c);
     else
      break;
    }
    String info = data.toString();
    System.out.println("输入的请求: " + info);

    // 接收到客户端的请求之后,将策略文件发送出去
    if (info.indexOf("<policy-file-request/>") >= 0) {
     writer.write(xml + "\0");
     writer.flush();
     System.out
       .println("将安全策略文件发送至: " + client.getInetAddress());
    } else {
     writer.write("请求无法识别/0");
     writer.flush();
     System.out.println("请求无法识别: " + client.getInetAddress());
    }
    client.close();
   } catch (Exception e) {
    e.printStackTrace();
    try {
     // 发现异常关闭连接
     if (client != null) {
      client.close();
      client = null;
     }
    } catch (IOException ex) {
     ex.printStackTrace();
    } finally {
     // 调用垃圾收集方法
     System.gc();
    }
   }
  }
 }

 // 测试主函数
 public static void main(String[] args) {
  new SecurityXMLServer();
 }
}

服务器主函数类:

package cn.jiabeis.socket;

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

public class SocketDemo {
 /**
  * 作者 张首尚
  */
 public static void main(String[] args) {
  ServerSocket ss = null;
  BufferedReader reader = null;
  BufferedWriter writer = null;
  try {
   new SecurityXMLServer();
   ss = new ServerSocket(2234);
   Socket socket = ss.accept();
   System.out.println("客户端已经连接成功");
   reader = new BufferedReader(new InputStreamReader(
     socket.getInputStream(), "UTF-8"));
   writer = new BufferedWriter(new OutputStreamWriter(
     socket.getOutputStream(),"UTF-8"));
   // while (true) {
   // if (reader.ready()) {
   // String str = reader.readLine();
   // System.out.println("socket" + str);
   // if (str.equals("fwq")) {
   // System.out.println("服务器回应\n");
   // writer.write("dfgdfg==============\n");
   // writer.flush();
   // }
   // if(str.indexOf("<policy-file-request/>") >= 0){
   // String xml = "<cross-domain-policy>\r\n"
   // +"<site-control permitted-cross-domain-policies=\"master-only\"/>\r\n"
   // + "<allow-access-from domain=\"*\" to-ports=\"1000-9999\"/>\r\n"
   // + "</cross-domain-policy>";
   // writer.write(xml + "\0");
   // writer.flush();
   // }
   // if (str.equals("tc")) {
   // if (reader != null) {
   // reader.close();
   // reader = null;
   // }
   // if (writer != null) {
   // writer.close();
   // writer = null;
   // }
   // socket.close();
   // ss.close();
   // break;
   // }
   // }
   // }
   String msg;
   while ((msg = reader.readLine()) != null) {
    writer.write(msg+"\n");
    writer.flush();
    System.out.println(msg);
   }
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

猜你喜欢

转载自blog.csdn.net/jiabeis/article/details/6730159
今日推荐