使用flash的Socket类连接服务器的任意端口

本文介绍如何使用mina2.0m1搭建一个简单的安全策略服务器,该服务器通过XMLSocket提供安全策略文件,允许Flash应用程序跨域访问指定端口。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Flash中有两个提供低层网络通信功能的类,Socket,XMLSocket . XMLSocket传输的是文本形式的xml字符串数据,每个数据单元以 0 结束. Socket可以传输任意类型的数据.
Flash 的安全模型下,缺省情况下,Socket 和XMLSocket只能连接到和swf文件同一个域上的大于1024的端口,但有些应用需要访问webserver之外的服务器上的端口,或者访问小于1024的端口,为了达到这种目的,需要使用安全策略文件,并在服务器端使用XMLSocket的协议提供这个安全策略文件.flash 在连接目标端口之前会先向策略服务端口发送一个请求:
“<policy-file-request/>”,策略服务接收到这个请求后需要返回一个策略文档,最后以0结束,当flash接收到 0时,会自动切断与策略服务的连接,并根据策略文件中的规则决定是否允许与目标端口连接.安全策略文件是一个xml格式的文档,例如: 


Xml代码 复制代码
  1. <SPAN style="FONT-SIZE: small"><cross-domain-policy>    
  2.    <allow-access-from domain="*" to-ports="507" />    
  3.    <allow-access-from domain="*.example.com" to-ports="507,516" />    
  4.    <allow-access-from domain="*.example.org" to-ports="516-523" />    
  5.    <allow-access-from domain="adobe.com" to-ports="507,516-523" />    
  6.    <allow-access-from domain="192.0.34.166" to-ports="*" />    
  7. </cross-domain-policy>  
  8. </SPAN>  


并且flash安全策略规定,如果这个文档是在小于1024的端口上提供,那么可以授权对所有端口的访问权限,如果在大于1024的端口上提供,则只能授权对大于1024的端口的访问权限.因此如果我们想要访问某台服务器上的任意端口的话,就需要在该服务器某个小于1024的端口上以XMLSocket的方式提供一个安全策略文件.
网上google了一把,发现没有类似功能的组件,于是自己动手写了一个,使用的网络框架是mina2.0m1,感谢mina提供的强大功能,我们只需要两个java类,数十行代码就可以完成一个简单的安全策略服务器.(本来xml文档识别的代码应该作为一个mina 的codec来开发,但因为这个例子的功能很简单,所以就偷了个懒,直接在IoHandler中处理了).代码如下:


  XmlSocketServer.java

 

Java代码 复制代码
  1. <SPAN style="FONT-SIZE: small">package net.mudfan.xmlsocket;   
  2.   
  3. import java.net.InetSocketAddress;   
  4. import java.nio.charset.Charset;   
  5. import org.apache.mina.common.DefaultIoFilterChainBuilder;   
  6. import org.apache.mina.filter.codec.ProtocolCodecFilter;   
  7. import org.apache.mina.filter.codec.textline.TextLineCodecFactory;   
  8. import org.apache.mina.transport.socket.SocketAcceptor;   
  9. import org.apache.mina.transport.socket.nio.NioSocketAcceptor;   
  10.   
  11. /**  
  12.  *  
  13.  * @author yunchang Yuan  
  14.  */  
  15. public class XmlSocketServer {   
  16.     private static final int PORT = 888;   
  17.     public static void main(String[] args) throws Exception{   
  18.         SocketAcceptor acceptor = new NioSocketAcceptor();   
  19.         DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();   
  20.         acceptor.setHandler(new XmlSocketHandler());   
  21.         acceptor.bind(new InetSocketAddress(PORT));   
  22.   
  23.         System.out.println("Listening on port " + PORT);   
  24.     }   
  25. }   
  26. </SPAN>  
package net.mudfan.xmlsocket;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import org.apache.mina.common.DefaultIoFilterChainBuilder;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

/**
 *
 * @author yunchang Yuan
 */
public class XmlSocketServer {
    private static final int PORT = 888;
    public static void main(String[] args) throws Exception{
        SocketAcceptor acceptor = new NioSocketAcceptor();
        DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
        acceptor.setHandler(new XmlSocketHandler());
        acceptor.bind(new InetSocketAddress(PORT));

        System.out.println("Listening on port " + PORT);
    }
}



 

XmlSocketHandler.java

 

 

Java代码 复制代码
  1. <SPAN style="FONT-SIZE: small">package net.mudfan.xmlsocket;   
  2.   
  3. import java.io.UnsupportedEncodingException;   
  4. import org.apache.mina.common.IdleStatus;   
  5. import org.apache.mina.common.IoBuffer;   
  6. import org.apache.mina.common.IoHandlerAdapter;   
  7. import org.apache.mina.common.IoSession;   
  8. import org.dom4j.Document;   
  9. import org.dom4j.DocumentHelper;   
  10. import org.slf4j.Logger;   
  11. import org.slf4j.LoggerFactory;   
  12.   
  13. /**  
  14.  *  
  15.  * @author yunchang Yuan  
  16.  */  
  17. public class XmlSocketHandler extends  IoHandlerAdapter{   
  18.     static Logger logger = LoggerFactory.getLogger(XmlSocketHandler.class);   
  19.     static String security_req = "<policy-file-request/>";   
  20.     static String allow_all =  "<cross-domain-policy>/n"+   
  21.                               "  <allow-access-from  domain=/"*/"  to-ports=/"*/"  />/n"+   
  22.                               "</cross-domain-policy>";   
  23.        
  24.     @Override  
  25.     public void exceptionCaught(IoSession arg0, Throwable arg1) throws Exception {   
  26.         super.exceptionCaught(arg0, arg1);   
  27.     }   
  28.   
  29.     @Override  
  30.     public void messageReceived(IoSession arg0, Object arg1) throws Exception {   
  31.         IoBuffer buf = (IoBuffer)arg1;   
  32.         IoBuffer processBuf = (IoBuffer)arg0.getAttribute("processBuf");   
  33.            
  34.         processBuf.put(buf);   
  35.         processBuf.flip();   
  36.         String req = getReq(processBuf);   
  37.         if(req!=null){   
  38.             if(security_req.equals(req)){   
  39.                 logger.info("get security req,now send policy file");    
  40.                 byte[] reps = allow_all.getBytes("UTF-8");   
  41.                 IoBuffer wb = IoBuffer.allocate(reps.length+1);   
  42.                 wb.put(reps);   
  43.                 wb.put((byte)0x0);   
  44.                 wb.flip();   
  45.                 arg0.write(wb);   
  46.                 arg0.setAttribute("policySend"true)    ;   
  47.             }   
  48.         }   
  49.            
  50.     }   
  51.   
  52.     @Override  
  53.     public void messageSent(IoSession arg0, Object arg1) throws Exception {   
  54.         logger.info("messageSent");   
  55.         arg0.close();   
  56.     }   
  57.   
  58.     @Override  
  59.     public void sessionClosed(IoSession arg0) throws Exception {           
  60.         logger.info("sessionClosed");       
  61.         super.sessionClosed(arg0);   
  62.         arg0.removeAttribute("processBuf");   
  63.     }   
  64.   
  65.     @Override  
  66.     public void sessionCreated(IoSession arg0) throws Exception {   
  67.         super.sessionCreated(arg0);   
  68.         IoBuffer processBuf = IoBuffer.allocate(64);   
  69.         arg0.setAttribute("processBuf", processBuf);   
  70.     }   
  71.   
  72.     @Override  
  73.     public void sessionIdle(IoSession arg0, IdleStatus arg1) throws Exception {   
  74.         super.sessionIdle(arg0, arg1);   
  75.     }   
  76.   
  77.     @Override  
  78.     public void sessionOpened(IoSession arg0) throws Exception {   
  79.         super.sessionOpened(arg0);   
  80.     }   
  81.   
  82.     private String getReq(IoBuffer buf) {   
  83.         IoBuffer reqbuf = IoBuffer.allocate(64);   
  84.         boolean found = false;   
  85.         for(int i=0;i<buf.limit();i++){   
  86.             byte data = buf.get();   
  87.             if(data!=0){   
  88.                 reqbuf.put(data);   
  89.             }else{   
  90.                 found = true;   
  91.                 break;   
  92.             }   
  93.         }   
  94.         if(found){   
  95.             logger.info("get xml document");   
  96.             reqbuf.flip();   
  97.             buf.compact();   
  98.             try {   
  99.                 byte[] strbuf = new byte[reqbuf.limit()];   
  100.                 reqbuf.get(strbuf,0,reqbuf.limit());   
  101.                 String req = new String(strbuf, "UTF-8");   
  102.                 logger.info("req is :"+req);   
  103.                 return req;   
  104.             } catch (UnsupportedEncodingException ex) {   
  105.                 logger.error("encoding error");   
  106.                 return null;   
  107.             }   
  108.                
  109.         }else{   
  110.                
  111.             return null;   
  112.         }   
  113.            
  114.     }   
  115.        
  116. }   
  117. </SPAN>  
package net.mudfan.xmlsocket;

import java.io.UnsupportedEncodingException;
import org.apache.mina.common.IdleStatus;
import org.apache.mina.common.IoBuffer;
import org.apache.mina.common.IoHandlerAdapter;
import org.apache.mina.common.IoSession;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author yunchang Yuan
 */
public class XmlSocketHandler extends  IoHandlerAdapter{
    static Logger logger = LoggerFactory.getLogger(XmlSocketHandler.class);
    static String security_req = "<policy-file-request/>";
    static String allow_all =  "<cross-domain-policy>/n"+
                              "  <allow-access-from  domain=/"*/"  to-ports=/"*/"  />/n"+
                              "</cross-domain-policy>";
    
    @Override
    public void exceptionCaught(IoSession arg0, Throwable arg1) throws Exception {
        super.exceptionCaught(arg0, arg1);
    }

    @Override
    public void messageReceived(IoSession arg0, Object arg1) throws Exception {
        IoBuffer buf = (IoBuffer)arg1;
        IoBuffer processBuf = (IoBuffer)arg0.getAttribute("processBuf");
        
        processBuf.put(buf);
        processBuf.flip();
        String req = getReq(processBuf);
        if(req!=null){
            if(security_req.equals(req)){
                logger.info("get security req,now send policy file"); 
                byte[] reps = allow_all.getBytes("UTF-8");
                IoBuffer wb = IoBuffer.allocate(reps.length+1);
                wb.put(reps);
                wb.put((byte)0x0);
                wb.flip();
                arg0.write(wb);
                arg0.setAttribute("policySend", true)    ;
            }
        }
        
    }

    @Override
    public void messageSent(IoSession arg0, Object arg1) throws Exception {
        logger.info("messageSent");
        arg0.close();
    }

    @Override
    public void sessionClosed(IoSession arg0) throws Exception {        
        logger.info("sessionClosed");    
        super.sessionClosed(arg0);
        arg0.removeAttribute("processBuf");
    }

    @Override
    public void sessionCreated(IoSession arg0) throws Exception {
        super.sessionCreated(arg0);
        IoBuffer processBuf = IoBuffer.allocate(64);
        arg0.setAttribute("processBuf", processBuf);
    }

    @Override
    public void sessionIdle(IoSession arg0, IdleStatus arg1) throws Exception {
        super.sessionIdle(arg0, arg1);
    }

    @Override
    public void sessionOpened(IoSession arg0) throws Exception {
        super.sessionOpened(arg0);
    }

    private String getReq(IoBuffer buf) {
        IoBuffer reqbuf = IoBuffer.allocate(64);
        boolean found = false;
        for(int i=0;i<buf.limit();i++){
            byte data = buf.get();
            if(data!=0){
                reqbuf.put(data);
            }else{
                found = true;
                break;
            }
        }
        if(found){
            logger.info("get xml document");
            reqbuf.flip();
            buf.compact();
            try {
                byte[] strbuf = new byte[reqbuf.limit()];
                reqbuf.get(strbuf,0,reqbuf.limit());
                String req = new String(strbuf, "UTF-8");
                logger.info("req is :"+req);
                return req;
            } catch (UnsupportedEncodingException ex) {
                logger.error("encoding error");
                return null;
            }
            
        }else{
            
            return null;
        }
        
    }
    
}



 

上面代码中用到的外部库,mina 2.0m1, sl4j1.5. 上述代码运行后在服务器的888端口上等待策略文件的请求,在flash代码中socket.connect() 调用之前加上 :
Security.loadPolicyFile("xmlsocket://host:888”); 这样,就可以让服务器上的所有端口被flash 连接了.如果要进行某种限制,修改策略文件即可. 当然也可以在此基础上扩展,从外部读取策略配置.
以上适用as3 的所有环境,包括flash 9+,flex2,flex3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值