智慧 + 毅力 = 无所不能

正确性、健壮性、可靠性、效率、易用性、可读性、可复用性、兼容性、可移植性...

导航

用flash socket发送http请求

Posted on 2010-04-28 18:19  Bill Yuan  阅读(4119)  评论(0编辑  收藏  举报
代码
package {
    
import flash.display.Sprite;
    
import flash.events.Event;
    
import flash.events.IOErrorEvent;
    
import flash.events.ProgressEvent;
    
import flash.net.Socket;
    
import flash.system.Security;
    
public class MySock extends Sprite
    {
        
public var port:int = 80;
        
public var host:String = "127.0.0.1";
        
public var sock:Socket;
        
public var response:String;
        
public function MySock()
        {
            sock 
= new Socket();
            sock.addEventListener(Event.CONNECT,connect);
            sock.addEventListener(Event.CLOSE,close);
            sock.addEventListener(ProgressEvent.SOCKET_DATA,dataHandler);
            sock.addEventListener(Event.COMPLETE,dataOk);
            Security.loadPolicyFile(
"http://"+host+":"+port+"/crossdomain.xml");  
            
            sock.addEventListener(IOErrorEvent.IO_ERROR,function(e:IOErrorEvent):
void{trace("ioerr");});
            start();
        }
        
//这里是收不到数据的
        public function dataOk(e:Event):void
        {
            trace(
"dataok:"+e.target.data);
        }
        
public function close(e:Event):void
        {
            trace(
"关闭了!");
        }
        
        
public function connect(e:Event):void
        {
            trace(
"连接成功!");
            var header:String 
= "GET /crossdomain.xml HTTP/1.1 rn";
            header 
+= "Accept: */* rn"
            header 
+= "Accept-Language: zh-cn rn";
            header 
+= "UA-CPU: x86 rn";
            header 
+= "Accept-Encoding: gzip, deflate rn";
            header 
+= "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ) rn";
            header 
+= "Host: " + host + ":" + port + " rn";
            header 
+= "Connection: Keep-Alive rn";
            header 
+= "Cache-Control: no-cache rnrn";
            
            sock.writeUTFBytes(header);
            
            sock.flush();
        }
        
//收到数据
        public function dataHandler(e:ProgressEvent):void
        {
            trace(
"dataHandler:"+e.bytesLoaded);
            var str:String 
= sock.readUTFBytes(sock.bytesAvailable);
            response 
+= str;
            
            
//if(e.bytesLoaded == e.bytesTotal)
            trace("response->"+response);
        }
        
public function start():void
        {
            sock.connect(host,port);
        }
    }