FlashSocke 經過flash進行socket通訊(as代碼)

    在早期的項目中, 由於須要用IE上鍊接socket進行通訊, 因此不得不借助於flash的socket功能,因而有了下面這個`FlashSocke`,供JavaScript調用 和 回調JavaScript.web

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         OnError(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             OnError(err.errorID,"接收數據時發生錯誤:"+err.toString());
 68         }
 69     }
 70 
 71     /*===============Flax調用JS函數==============================================*/
 72 
 73     //調用JS函數OnError,出錯回調
 74     public function OnError(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 OnError(-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 OnError(err.errorID,"鏈接時發生錯誤:"+err.toString()),0;
143         }
144     }
145 
146     //JS調用Close,關閉Socket
147     public function Close()
148     {//trace("Close.................");
149         try
150         {
151             socket.close();
152         }
153         catch (err:Error)
154         {
155             OnError(err.errorID,"關閉Socket時發生錯誤:"+err.toString());
156         }
157         bConnecting=false;
158     }
159     //JS調用GetState,返回Socket鏈接狀態
160     public function GetState():Boolean
161     {
162         try
163         {
164             if(socket!=null)
165                 return socket.connected;
166             else
167                 return false;
168         }
169         catch(err:Error)
170         {
171             OnError(err.errorID,"GetState發生錯誤:"+err.toString());
172         }
173         return false;
174     }
175     //JS調用Send,發送數據,返回發送的數據的長度
176     public function SendMsg(msg:String):int
177     {
178         var len:int = 0;
179         if (socket && socket.connected)
180         {
181             try
182             {
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                 OnError(err.errorID,"發送數據時發生錯誤:"+err.toString());
197             }
198         }
199         else
200         {
201             len = -96;
202             OnError(-96,"未鏈接或已斷開,須要從新鏈接/登錄.");
203         }
204         return len;
205     }
206 
207 }//End class Main
208 
209 }//end package
View Code

固然,後來 瀏覽器們都紛紛更新,支持H5, 就是用WebSocket了, 因而再也不是用這個破舊的東西了, 畢竟是插件嘛, 穩定性啥的,,,,(ps:flash會常常崩潰呀)服務器

調用說明:dom

[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,關閉Socket
Close():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` 就能夠使用了.異步

要注意異步.socket

相關文章
相關標籤/搜索