首页 > 代码库 > FlashSocke 通过flash进行socket通信(as代码)

FlashSocke 通过flash进行socket通信(as代码)

    在早期的项目中, 因为需要用IE上连接socket进行通信, 所以不得不借助于flash的socket功能,于是有了下面这个`FlashSocke`,供JavaScript调用 和 回调JavaScript.

code:

技术分享
  1 package  2 {  3 import flash.external.*;  4 import flash.display.Sprite;  5 //import flash.external.ExternalInterface;  6 import flash.events.*;  7 import flash.net.Socket;  8 import flash.system.*;  9 import flash.utils.Timer; 10  11 //============================================================================== 12 public class Main extends Sprite 13 { 14     static var socket:Socket = null; 15     static var bConnecting:Boolean = false; 16     static var charSet:String; 17     static var Obj:String; 18     static var ReConNum:Number=0; 19     //var str:String; 20  21     public function Main() 22     { 23         //添加JS调用的函数的接口。 24         ExternalInterface.addCallback("Connect",Connect); 25         ExternalInterface.addCallback("SendMsg",SendMsg); 26         ExternalInterface.addCallback("Close",Close); 27         ExternalInterface.addCallback("GetState",GetState); 28     } 29     //事件回调,当连接更改时 30     public function OnConnect(evt:Event=null):void 31     { 32         if(socket.connected) 33             bConnecting=false; 34         Debug(evt.toString()); 35         ExternalInterface.call(Obj+"OnConnect",socket.connected); 36     } 37     //事件回调,被动关闭才会触发 38     public function OnClose(evt:Event):void 39     { 40         Debug(evt.toString()); 41         bConnecting=false; 42         ExternalInterface.call(Obj+"OnClose"); 43     } 44  45     /*===============Flax事件回调函数==============================================*/ 46  47     //事件回调,出错回调 48     public function errorHandler(evt:ErrorEvent):void 49     { 50         one rror(evt.errorID,evt.toString()); 51     } 52     //事件回调,接收回调 53     public function ReciveHandler(evt:ProgressEvent):void 54     { 55         try 56         { 57             //OnMsg( socket.readUTFBytes(socket.bytesAvailable) );//UTF 58             //OnMsg( socket.readUTF());//Error #2030 59             //str=socket.readMultiByte(socket.bytesAvailable,charSet); 60             //Debug(str); 61             //ExternalInterface.call(Obj+"OnMsg",str.replace(new RegExp("\\", ‘g‘),"\\\\")); 62             ExternalInterface.call(Obj+"OnMsg",socket.readMultiByte(socket.bytesAvailable,charSet).replace(/\\/g,"\\\\")); 63             //OnMsg(socket.readMultiByte(socket.bytesAvailable,charSet)); 64         } 65         catch (err:Error) 66         { 67             one rror(err.errorID,"接收数据时发生错误:"+err.toString()); 68         } 69     } 70  71     /*===============Flax调用JS函数==============================================*/ 72  73     //调用JS函数OnError,出错回调 74     public function one rror(code:int,msg:String):int 75     { 76         ExternalInterface.call(Obj+"OnError",code,msg); 77         return code; 78     } 79     //调用JS函数Logs,显示日志信息 80     public function Debug(str:String):void 81     { 82         ExternalInterface.call(Obj+"Logs","[Flash]"+str); 83     } 84  85     /*===============JS调用Flax函数==============================================*/ 86  87     //通过JS调用Connect,初始化Socket,并连接 88     public function Connect(ip:String, port:int, obj:String="", charset:String="GBK", pf:String="") 89     { 90         //trace("Connect..."); 91         try 92         { 93             if (socket && socket.connected) 94             { 95                 ExternalInterface.call(Obj+"OnMsg","{}"); 96                 return Debug("已连接"),1; 97             } 98             if(bConnecting&&ReConNum<10)//连接次数小于10 99             {100                 ReConNum++;101                 return Debug("连接中... Connecting... Wait Please."),1;102             }103             ReConNum=0;104             if (ip == "" || port == 0)105                 return one rror(-99,"不正确的IP或端口参数"),0;106 107             charSet=charset;108             if(obj!="")109                 Obj=obj+".";//JS对象名; 这样可以调用JS对象的函数110 111             Debug("Ver:2015-1120-1720");112             Debug("Connect("+ip+", "+port+")");113             114             try{115               if(socket!=null)116                 socket.close();117             }catch (error1:Error){}118 119             bConnecting=true;120             121             socket = new Socket  ;122             socket.timeout = 10000;//超时事件会被捕获为securityError事件,不知道为啥123             socket.addEventListener(Event.CONNECT,OnConnect);//连接状态变化时,经常不执行;用定时器检查去了124             socket.addEventListener(Event.CLOSE,OnClose);125             socket.addEventListener(ErrorEvent.ERROR,errorHandler);126             socket.addEventListener(IOErrorEvent.IO_ERROR,errorHandler);127             socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR,errorHandler);128             socket.addEventListener(ProgressEvent.SOCKET_DATA,ReciveHandler,false,0,true);129 130             //"http://" + serverIP + ":" + webport + "/crossdomain.xml";131             //Security.allowDomain("*");132             if (pf != "")133                 Security.loadPolicyFile(pf);134 135             socket.connect(ip,port);//连接是异步的136             return 1;137         }138         catch (err:Error)139         {140             bConnecting=false;141             socket.close();142             return one rror(err.errorID,"连接时发生错误:"+err.toString()),0;143         }144     }145 146     //JS调用Close,关闭Socket147     public function Close()148     {//trace("Close.................");149         try150         {151             socket.close();152         }153         catch (err:Error)154         {155             one rror(err.errorID,"关闭Socket时发生错误:"+err.toString());156         }157         bConnecting=false;158     }159     //JS调用GetState,返回Socket连接状态160     public function GetState():Boolean161     {162         try163         {164             if(socket!=null)165                 return socket.connected;166             else167                 return false;168         }169         catch(err:Error)170         {171             one rror(err.errorID,"GetState发生错误:"+err.toString());172         }173         return false;174     }175     //JS调用Send,发送数据,返回发送的数据的长度176     public function SendMsg(msg:String):int177     {178         var len:int = 0;179         if (socket && socket.connected)180         {181             try182             {183                 //var ba:ByteArray = new ByteArray ;184                 //ba.writeUTFBytes(msg);185                 //socket.writeBytes(ba);186                 socket.writeMultiByte(msg,charSet);187                 //socket.writeUTF(msg+"\n");188                 socket.flush();189                 //sleep(50);190                 len = msg.length;191                 Debug("SendMsgLen:"+len);192             }193             catch (err:Error)194             {195                 len = err.errorID;196                 one rror(err.errorID,"发送数据时发生错误:"+err.toString());197             }198         }199         else200         {201             len = -96;202             one rror(-96,"未连接或已断开,需要重新连接/登陆.");203         }204         return len;205     }206 207 }//End class Main208 209 }//end package
View Code

当然,后来 浏览器们都纷纷更新,支持H5, 就是用WebSocket了, 于是不再是用这个破旧的东西了, 毕竟是插件嘛, 稳定性啥的,,,,(ps:flash会经常崩溃呀)

调用说明:

[FlashSocket:提供的函数接口]//通过JS调用Connect,初始化Socket,并连接//obj:设置函数的回调前缀(对象名,如:"fsObj"),使能回调象的函数(如"fsObj.OnMsg")//charset:设置往来消息的字符编码,默认编码"GBK"//pf:设置Security.loadPolicyFile 的地址Connect(ip:String, port:int, obj:String="", charset:String="GBK", pf:String=""):void//通过JS调用SendMsg,发送数据,返回发送的数据的长度SendMsg(msg:String):int//通过JS调用Close,关闭SocketClose():void//通过JS调用GetState,返回Socket连接状态。GetState():Boolean//通过JS调用GetServerIP,返回服务器IP地址GetServerIP():String//通过JS调用GetServerPort,返回服务器端口GetServerPort():int[JavaScript:提供的回调函数接口]OnConnect(bool)OnClose()OnError(code,msg)OnMsg(msgstr)Logs(logstr)

那啥,编译成 `.swf` 就可以使用了.

要注意异步.

FlashSocke 通过flash进行socket通信(as代码)