nyoibo 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,157 @@
1
+ ## How to try the sample
2
+
3
+ Assuming you have Web server (e.g. Apache) running at **http://example.com/** .
4
+
5
+ 1. Download [web-socket-ruby](http://github.com/gimite/web-socket-ruby/tree/master).
6
+ 2. Run sample Web Socket server (echo server) in example.com with: (#1)<br>
7
+ ```
8
+ $ ruby web-socket-ruby/samples/echo_server.rb example.com 10081
9
+ ```
10
+ 3. If your server already provides socket policy file at port **843**, modify the file to allow access to port **10081**. Otherwise you can skip this step. See below for details.
11
+ 4. Publish the web-socket-js directory with your Web server (e.g. put it in ~/public_html).
12
+ 5. Change ws://localhost:10081 to **ws://example.com:10081** in sample.html.
13
+ 6. Open sample.html in your browser.
14
+ 7. After "onopen" is shown, input something, click [Send] and confirm echo back.
15
+
16
+ \#1: First argument of echo_server.rb means that it accepts Web Socket connection from HTML pages in example.com.
17
+
18
+
19
+ ## How to use it in your application
20
+
21
+ - Copy swfobject.js, web_socket.js, WebSocketMain.swf to your application directory.
22
+ - Write JavaScript code:
23
+
24
+ ```html
25
+ <!-- Import JavaScript Libraries. -->
26
+ <script type="text/javascript" src="swfobject.js"></script>
27
+ <script type="text/javascript" src="web_socket.js"></script>
28
+
29
+ <script type="text/javascript">
30
+
31
+ // Let the library know where WebSocketMain.swf is:
32
+ WEB_SOCKET_SWF_LOCATION = "WebSocketMain.swf";
33
+
34
+ // Write your code in the same way as for native WebSocket:
35
+ var ws = new WebSocket("ws://example.com:10081/");
36
+ ws.onopen = function() {
37
+ ws.send("Hello"); // Sends a message.
38
+ };
39
+ ws.onmessage = function(e) {
40
+ // Receives a message.
41
+ alert(e.data);
42
+ };
43
+ ws.onclose = function() {
44
+ alert("closed");
45
+ };
46
+
47
+ </script>
48
+ ```
49
+
50
+ - Put Flash socket policy file to your server unless you use web-socket-ruby or em-websocket as your WebSocket server. See "Flash socket policy file" section below for details.
51
+
52
+
53
+ ## Troubleshooting
54
+
55
+ If it doesn't work, try these:
56
+
57
+ 1. Try Chrome and Firefox 3.x.
58
+
59
+ - It doesn't work on Chrome:<br>
60
+ It's likely an issue of your code or the server. Debug your code as usual e.g. using console.log.
61
+ - It works on Chrome but it doesn't work on Firefox:<br>
62
+ It's likely an issue of web-socket-js specific configuration (e.g. 3 and 4 below).
63
+ - It works on both Chrome and Firefox, but it doesn't work on your browser:<br>
64
+ Check "Supported environment" section below. Your browser may not be supported by web-socket-js.
65
+
66
+ 2. Add this line before your code:
67
+ WEB_SOCKET_DEBUG = true;
68
+ and use Developer Tools (Chrome/Safari) or Firebug (Firefox) to see if console.log outputs any errors.
69
+
70
+ 3. Make sure you do NOT open your HTML page as local file e.g. file:///.../sample.html. web-socket-js doesn't work on local file. Open it via Web server e.g. http:///.../sample.html.
71
+
72
+ 4. If you are NOT using web-socket-ruby or em-websocket as your WebSocket server, you need to place Flash socket policy file on your server. See "Flash socket policy file" section below for details.
73
+
74
+ 5. Check if sample.html bundled with web-socket-js works.
75
+
76
+ 6. Make sure the port used for WebSocket (10081 in example above) is not blocked by your server/client's firewall.
77
+
78
+ 7. Install [debugger version of Flash Player](http://www.adobe.com/support/flashplayer/downloads.html) to see Flash errors.
79
+
80
+
81
+ ## Supported environments
82
+
83
+ It should work on:
84
+
85
+ - Google Chrome 4 or later (just uses native implementation)
86
+ - Firefox 3.x, 4.x, Internet Explorer 8, 9 + Flash Player 10 or later
87
+
88
+ It may or may not work on other browsers such as Safari, Opera or IE 6. Patch for these browsers are appreciated, but I will not work on fixing issues specific to these browsers by myself.
89
+
90
+
91
+ ## Limitations/differences compared to native WebSocket
92
+
93
+ - You need some more lines in your JavaScript code. See "How to use it in your application" section above for details.
94
+ - It requires Flash Player 10 or later unless the browser supports native WebSocket.
95
+ - Your server must provide Flash socket policy file, unless you use web-socket-ruby or em-websocket. See "Flash socket policy file" section below for details.
96
+ - It has limited support for Cookies on WebSocket. See "Cookie support" section below for details.
97
+ - It doesn't use proxies specified in browser config. See "Proxy support" section below for details.
98
+
99
+
100
+ ### Flash socket policy file
101
+
102
+ This implementation uses Flash's socket, which means that your server must provide Flash socket policy file to declare the server accepts connections from Flash.
103
+
104
+ If you use [web-socket-ruby](http://github.com/gimite/web-socket-ruby/tree/master) or [em-websocket](https://github.com/igrigorik/em-websocket), you don't need anything special, because they handle Flash socket policy file request. But if you already provide socket policy file at port **843**, you need to modify the file to allow access to Web Socket port, because it precedes what the libraries provide.
105
+
106
+ If you use other Web Socket server implementation, you need to provide socket policy file yourself. See [Setting up A Flash Socket Policy File](http://www.lightsphere.com/dev/articles/flash_socket_policy.html) for details and sample script to run socket policy file server. [node.js implementation is available here](http://github.com/LearnBoost/Socket.IO-node/blob/master/lib/socket.io/transports/flashsocket.js).
107
+
108
+ Actually, it's still better to provide socket policy file at port 843 even if you use web-socket-ruby or em-websocket. Flash always try to connect to port 843 first, so providing the file at port 843 makes startup faster.
109
+
110
+
111
+ ### Cookie support
112
+
113
+ web-socket-js has limited supported for Cookies on WebSocket.
114
+
115
+ Cookie is sent if Web Socket host is exactly the same as the origin of JavaScript (The port can be different). Otherwise it is not sent, because I don't know way to send right Cookie (which is Cookie of the host of Web Socket, I heard). Also, HttpOnly Cookies are not sent.
116
+
117
+ Note that it's technically possible that client sends arbitrary string as Cookie and any other headers (by modifying this library for example) once you place Flash socket policy file in your server. So don't trust Cookie and other headers if you allow connection from untrusted origin.
118
+
119
+
120
+ ### Proxy support
121
+
122
+ [The WebSocket spec](http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol) specifies instructions for User Agents to support proxied connections by implementing the HTTP CONNECT method.
123
+
124
+ The AS3 Socket class doesn't implement this mechanism, which renders it useless for the scenarios where the user trying to open a socket is behind a proxy.
125
+
126
+ The class RFC2817Socket (by Christian Cantrell) effectively lets us implement this, as long as the proxy settings are known and provided by the interface that instantiates the WebSocket. As such, if you want to support proxied conncetions, you'll have to supply this information to the WebSocket constructor when Flash is being used. One way to go about it would be to ask the user for proxy settings information if the initial connection fails.
127
+
128
+
129
+ ## How to host HTML file and SWF file in different domains
130
+
131
+ By default, HTML file and SWF file must be in the same domain. You can follow steps below to allow hosting them in different domain.
132
+
133
+ **WARNING**: If you use the method below, HTML files in ANY domains can send arbitrary TCP data to your WebSocket server, regardless of configuration in Flash socket policy file. Arbitrary TCP data means that they can even fake request headers including Origin and Cookie.
134
+
135
+ 1. Unzip WebSocketMainInsecure.zip to extract WebSocketMainInsecure.swf.
136
+ 2. Put WebSocketMainInsecure.swf on your server, instead of WebSocketMain.swf.
137
+ 3. In JavaScript, set WEB_SOCKET_SWF_LOCATION to URL of your WebSocketMainInsecure.swf.
138
+
139
+
140
+ ## How to build WebSocketMain.swf
141
+
142
+ Install [Flex 4 SDK](http://opensource.adobe.com/wiki/display/flexsdk/Download+Flex+4).
143
+
144
+ $ cd flash-src
145
+ $ ./build.sh
146
+
147
+
148
+ ## WebSocket protocol versions
149
+
150
+ - web-socket-js supports [Hixie 76 version](http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76) of WebSocket protocol by default i.e. in [master branch](https://github.com/gimite/web-socket-js).
151
+ - If you want to try newer [Hybi 07 version](http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-07), check out from [hybi-07 branch](https://github.com/gimite/web-socket-js/tree/hybi-07). This will become the master branch in the future, probably when Chrome switches to Hybi 07.
152
+ - Hixie 75 or before is no longer supported.
153
+
154
+
155
+ ## License
156
+
157
+ New BSD License.
@@ -0,0 +1,4 @@
1
+ /* SWFObject v2.2 <http://code.google.com/p/swfobject/>
2
+ is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
3
+ */
4
+ var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();
@@ -0,0 +1,361 @@
1
+ // Copyright: Hiroshi Ichikawa <http://gimite.net/en/>
2
+ // License: New BSD License
3
+ // Reference: http://dev.w3.org/html5/websockets/
4
+ // Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol
5
+
6
+ (function() {
7
+
8
+ if (window.WebSocket) return;
9
+
10
+ var console = window.console;
11
+ if (!console || !console.log || !console.error) {
12
+ console = {log: function(){ }, error: function(){ }};
13
+ }
14
+
15
+ // swfobject.hasFlashPlayerVersion("10.0.0") doesn't work with Gnash.
16
+ if (!swfobject.getFlashPlayerVersion().major >= 10) {
17
+ console.error("Flash Player >= 10.0.0 is required.");
18
+ return;
19
+ }
20
+ if (location.protocol == "file:") {
21
+ console.error(
22
+ "WARNING: web-socket-js doesn't work in file:///... URL " +
23
+ "unless you set Flash Security Settings properly. " +
24
+ "Open the page via Web server i.e. http://...");
25
+ }
26
+
27
+ /**
28
+ * This class represents a faux web socket.
29
+ * @param {string} url
30
+ * @param {array or string} protocols
31
+ * @param {string} proxyHost
32
+ * @param {int} proxyPort
33
+ * @param {string} headers
34
+ */
35
+ WebSocket = function(url, protocols, proxyHost, proxyPort, headers) {
36
+ var self = this;
37
+ self.__id = WebSocket.__nextId++;
38
+ WebSocket.__instances[self.__id] = self;
39
+ self.readyState = WebSocket.CONNECTING;
40
+ self.bufferedAmount = 0;
41
+ self.__events = {};
42
+ if (!protocols) {
43
+ protocols = [];
44
+ } else if (typeof protocols == "string") {
45
+ protocols = [protocols];
46
+ }
47
+ // Uses setTimeout() to make sure __createFlash() runs after the caller sets ws.onopen etc.
48
+ // Otherwise, when onopen fires immediately, onopen is called before it is set.
49
+ setTimeout(function() {
50
+ WebSocket.__addTask(function() {
51
+ WebSocket.__flash.create(
52
+ self.__id, url, protocols, proxyHost || null, proxyPort || 0, headers || null);
53
+ });
54
+ }, 0);
55
+ };
56
+
57
+ /**
58
+ * Send data to the web socket.
59
+ * @param {string} data The data to send to the socket.
60
+ * @return {boolean} True for success, false for failure.
61
+ */
62
+ WebSocket.prototype.send = function(data) {
63
+ if (this.readyState == WebSocket.CONNECTING) {
64
+ throw "INVALID_STATE_ERR: Web Socket connection has not been established";
65
+ }
66
+ // We use encodeURIComponent() here, because FABridge doesn't work if
67
+ // the argument includes some characters. We don't use escape() here
68
+ // because of this:
69
+ // https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#escape_and_unescape_Functions
70
+ // But it looks decodeURIComponent(encodeURIComponent(s)) doesn't
71
+ // preserve all Unicode characters either e.g. "\uffff" in Firefox.
72
+ // Note by wtritch: Hopefully this will not be necessary using ExternalInterface. Will require
73
+ // additional testing.
74
+ var result = WebSocket.__flash.send(this.__id, encodeURIComponent(data));
75
+ if (result < 0) { // success
76
+ return true;
77
+ } else {
78
+ this.bufferedAmount += result;
79
+ return false;
80
+ }
81
+ };
82
+
83
+ /**
84
+ * Close this web socket gracefully.
85
+ */
86
+ WebSocket.prototype.close = function() {
87
+ if (this.readyState == WebSocket.CLOSED || this.readyState == WebSocket.CLOSING) {
88
+ return;
89
+ }
90
+ this.readyState = WebSocket.CLOSING;
91
+ WebSocket.__flash.close(this.__id);
92
+ };
93
+
94
+ /**
95
+ * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
96
+ *
97
+ * @param {string} type
98
+ * @param {function} listener
99
+ * @param {boolean} useCapture
100
+ * @return void
101
+ */
102
+ WebSocket.prototype.addEventListener = function(type, listener, useCapture) {
103
+ if (!(type in this.__events)) {
104
+ this.__events[type] = [];
105
+ }
106
+ this.__events[type].push(listener);
107
+ };
108
+
109
+ /**
110
+ * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
111
+ *
112
+ * @param {string} type
113
+ * @param {function} listener
114
+ * @param {boolean} useCapture
115
+ * @return void
116
+ */
117
+ WebSocket.prototype.removeEventListener = function(type, listener, useCapture) {
118
+ if (!(type in this.__events)) return;
119
+ var events = this.__events[type];
120
+ for (var i = events.length - 1; i >= 0; --i) {
121
+ if (events[i] === listener) {
122
+ events.splice(i, 1);
123
+ break;
124
+ }
125
+ }
126
+ };
127
+
128
+ /**
129
+ * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
130
+ *
131
+ * @param {Event} event
132
+ * @return void
133
+ */
134
+ WebSocket.prototype.dispatchEvent = function(event) {
135
+ var events = this.__events[event.type] || [];
136
+ for (var i = 0; i < events.length; ++i) {
137
+ events[i](event);
138
+ }
139
+ var handler = this["on" + event.type];
140
+ if (handler) handler(event);
141
+ };
142
+
143
+ /**
144
+ * Handles an event from Flash.
145
+ * @param {Object} flashEvent
146
+ */
147
+ WebSocket.prototype.__handleEvent = function(flashEvent) {
148
+ if ("readyState" in flashEvent) {
149
+ this.readyState = flashEvent.readyState;
150
+ }
151
+ if ("protocol" in flashEvent) {
152
+ this.protocol = flashEvent.protocol;
153
+ }
154
+
155
+ var jsEvent;
156
+ if (flashEvent.type == "open" || flashEvent.type == "error") {
157
+ jsEvent = this.__createSimpleEvent(flashEvent.type);
158
+ } else if (flashEvent.type == "close") {
159
+ // TODO implement jsEvent.wasClean
160
+ jsEvent = this.__createSimpleEvent("close");
161
+ } else if (flashEvent.type == "message") {
162
+ var data = decodeURIComponent(flashEvent.message);
163
+ jsEvent = this.__createMessageEvent("message", data);
164
+ } else {
165
+ throw "unknown event type: " + flashEvent.type;
166
+ }
167
+
168
+ this.dispatchEvent(jsEvent);
169
+ };
170
+
171
+ WebSocket.prototype.__createSimpleEvent = function(type) {
172
+ if (document.createEvent && window.Event) {
173
+ var event = document.createEvent("Event");
174
+ event.initEvent(type, false, false);
175
+ return event;
176
+ } else {
177
+ return {type: type, bubbles: false, cancelable: false};
178
+ }
179
+ };
180
+
181
+ WebSocket.prototype.__createMessageEvent = function(type, data) {
182
+ if (document.createEvent && window.MessageEvent && !window.opera) {
183
+ var event = document.createEvent("MessageEvent");
184
+ event.initMessageEvent("message", false, false, data, null, null, window, null);
185
+ return event;
186
+ } else {
187
+ // IE and Opera, the latter one truncates the data parameter after any 0x00 bytes.
188
+ return {type: type, data: data, bubbles: false, cancelable: false};
189
+ }
190
+ };
191
+
192
+ /**
193
+ * Define the WebSocket readyState enumeration.
194
+ */
195
+ WebSocket.CONNECTING = 0;
196
+ WebSocket.OPEN = 1;
197
+ WebSocket.CLOSING = 2;
198
+ WebSocket.CLOSED = 3;
199
+
200
+ WebSocket.__flash = null;
201
+ WebSocket.__instances = {};
202
+ WebSocket.__tasks = [];
203
+ WebSocket.__nextId = 0;
204
+
205
+ /**
206
+ * Load a new flash security policy file.
207
+ * @param {string} url
208
+ */
209
+ WebSocket.loadFlashPolicyFile = function(url){
210
+ WebSocket.__addTask(function() {
211
+ WebSocket.__flash.loadManualPolicyFile(url);
212
+ });
213
+ };
214
+
215
+ /**
216
+ * Loads WebSocketMain.swf and creates WebSocketMain object in Flash.
217
+ */
218
+ WebSocket.__initialize = function() {
219
+ if (WebSocket.__flash) return;
220
+
221
+ if (WebSocket.__swfLocation) {
222
+ // For backword compatibility.
223
+ window.WEB_SOCKET_SWF_LOCATION = WebSocket.__swfLocation;
224
+ }
225
+ if (!window.WEB_SOCKET_SWF_LOCATION) {
226
+ console.error("[WebSocket] set WEB_SOCKET_SWF_LOCATION to location of WebSocketMain.swf");
227
+ return;
228
+ }
229
+ if (!WEB_SOCKET_SWF_LOCATION.match(/(^|\/)WebSocketMainInsecure\.swf(\?.*)?$/) &&
230
+ WEB_SOCKET_SWF_LOCATION.match(/^\w+:\/\/([^\/]+)/)) {
231
+ var swfHost = RegExp.$1;
232
+ if (location.host != swfHost) {
233
+ console.error(
234
+ "[WebSocket] You must host HTML and WebSocketMain.swf in the same host " +
235
+ "('" + location.host + "' != '" + swfHost + "'). " +
236
+ "See also 'How to host HTML file and SWF file in different domains' section " +
237
+ "in README.md.");
238
+ }
239
+ }
240
+ var container = document.createElement("div");
241
+ container.id = "webSocketContainer";
242
+ // Hides Flash box. We cannot use display: none or visibility: hidden because it prevents
243
+ // Flash from loading at least in IE. So we move it out of the screen at (-100, -100).
244
+ // But this even doesn't work with Flash Lite (e.g. in Droid Incredible). So with Flash
245
+ // Lite, we put it at (0, 0). This shows 1x1 box visible at left-top corner but this is
246
+ // the best we can do as far as we know now.
247
+ container.style.position = "absolute";
248
+ if (WebSocket.__isFlashLite()) {
249
+ container.style.left = "0px";
250
+ container.style.top = "0px";
251
+ } else {
252
+ container.style.left = "-100px";
253
+ container.style.top = "-100px";
254
+ }
255
+ var holder = document.createElement("div");
256
+ holder.id = "webSocketFlash";
257
+ container.appendChild(holder);
258
+ document.body.appendChild(container);
259
+ // See this article for hasPriority:
260
+ // http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html
261
+ swfobject.embedSWF(
262
+ WEB_SOCKET_SWF_LOCATION,
263
+ "webSocketFlash",
264
+ "1" /* width */,
265
+ "1" /* height */,
266
+ "10.0.0" /* SWF version */,
267
+ null,
268
+ null,
269
+ {hasPriority: true, swliveconnect : true, allowScriptAccess: "always"},
270
+ null,
271
+ function(e) {
272
+ if (!e.success) {
273
+ console.error("[WebSocket] swfobject.embedSWF failed");
274
+ }
275
+ });
276
+ };
277
+
278
+ /**
279
+ * Called by Flash to notify JS that it's fully loaded and ready
280
+ * for communication.
281
+ */
282
+ WebSocket.__onFlashInitialized = function() {
283
+ // We need to set a timeout here to avoid round-trip calls
284
+ // to flash during the initialization process.
285
+ setTimeout(function() {
286
+ WebSocket.__flash = document.getElementById("webSocketFlash");
287
+ WebSocket.__flash.setCallerUrl(location.href);
288
+ WebSocket.__flash.setDebug(!!window.WEB_SOCKET_DEBUG);
289
+ for (var i = 0; i < WebSocket.__tasks.length; ++i) {
290
+ WebSocket.__tasks[i]();
291
+ }
292
+ WebSocket.__tasks = [];
293
+ }, 0);
294
+ };
295
+
296
+ /**
297
+ * Called by Flash to notify WebSockets events are fired.
298
+ */
299
+ WebSocket.__onFlashEvent = function() {
300
+ setTimeout(function() {
301
+ try {
302
+ // Gets events using receiveEvents() instead of getting it from event object
303
+ // of Flash event. This is to make sure to keep message order.
304
+ // It seems sometimes Flash events don't arrive in the same order as they are sent.
305
+ var events = WebSocket.__flash.receiveEvents();
306
+ for (var i = 0; i < events.length; ++i) {
307
+ WebSocket.__instances[events[i].webSocketId].__handleEvent(events[i]);
308
+ }
309
+ } catch (e) {
310
+ console.error(e);
311
+ }
312
+ }, 0);
313
+ return true;
314
+ };
315
+
316
+ // Called by Flash.
317
+ WebSocket.__log = function(message) {
318
+ console.log(decodeURIComponent(message));
319
+ };
320
+
321
+ // Called by Flash.
322
+ WebSocket.__error = function(message) {
323
+ console.error(decodeURIComponent(message));
324
+ };
325
+
326
+ WebSocket.__addTask = function(task) {
327
+ if (WebSocket.__flash) {
328
+ task();
329
+ } else {
330
+ WebSocket.__tasks.push(task);
331
+ }
332
+ };
333
+
334
+ /**
335
+ * Test if the browser is running flash lite.
336
+ * @return {boolean} True if flash lite is running, false otherwise.
337
+ */
338
+ WebSocket.__isFlashLite = function() {
339
+ if (!window.navigator || !window.navigator.mimeTypes) {
340
+ return false;
341
+ }
342
+ var mimeType = window.navigator.mimeTypes["application/x-shockwave-flash"];
343
+ if (!mimeType || !mimeType.enabledPlugin || !mimeType.enabledPlugin.filename) {
344
+ return false;
345
+ }
346
+ return mimeType.enabledPlugin.filename.match(/flashlite/i) ? true : false;
347
+ };
348
+
349
+ if (!window.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION) {
350
+ if (window.addEventListener) {
351
+ window.addEventListener("load", function(){
352
+ WebSocket.__initialize();
353
+ }, false);
354
+ } else {
355
+ window.attachEvent("onload", function(){
356
+ WebSocket.__initialize();
357
+ });
358
+ }
359
+ }
360
+
361
+ })();