Code Monkey home page Code Monkey logo

web-socket-js's Introduction

How to try the sample

Assuming you have Web server (e.g. Apache) running at http://example.com/ .

  1. Download web-socket-ruby.
  2. Run sample Web Socket server (echo server) in example.com with: (#1)
$ ruby web-socket-ruby/samples/echo_server.rb example.com 10081
  1. 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.
  2. Publish the web-socket-js directory with your Web server (e.g. put it in ~/public_html).
  3. Change ws://localhost:10081 to ws://example.com:10081 in sample.html.
  4. Open sample.html in your browser.
  5. After "onopen" is shown, input something, click [Send] and confirm echo back.

#1: First argument of echo_server.rb means that it accepts Web Socket connection from HTML pages in example.com.

How to use it in your application

  • Copy swfobject.js, web_socket.js, WebSocketMain.swf to your application directory.
  • Write JavaScript code:
<!-- Import JavaScript Libraries. -->
<script type="text/javascript" src="swfobject.js"></script>
<script type="text/javascript" src="web_socket.js"></script>

<script type="text/javascript">
  
  // Let the library know where WebSocketMain.swf is:
  WEB_SOCKET_SWF_LOCATION = "WebSocketMain.swf";
  
  // Write your code in the same way as for native WebSocket:
  var ws = new WebSocket("ws://example.com:10081/");
  ws.onopen = function() {
    ws.send("Hello");  // Sends a message.
  };
  ws.onmessage = function(e) {
    // Receives a message.
    alert(e.data);
  };
  ws.onclose = function() {
    alert("closed");
  };
  
</script>
  • 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.

Troubleshooting

If it doesn't work, try these:

  1. Try Chrome and IE 8 or 9.

    • It doesn't work on Chrome:
      It's likely an issue of your code or the server. Debug your code as usual e.g. using console.log.
    • It works on Chrome but it doesn't work on IE:
      It's likely an issue of web-socket-js specific configuration (e.g. 3 and 4 below).
    • It works on both Chrome and IE, but it doesn't work on your browser:
      Check "Supported environment" section below. Your browser may not be supported by web-socket-js.
  2. Add this line before your code: WEB_SOCKET_DEBUG = true; and use Developer Tools (Chrome/Safari) or Firebug (Firefox) to see if console.log outputs any errors.

  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.

  4. Make sure you host your HTML page and WebSocketMain.swf in the same domain. Otherwise, see "How to host HTML file and SWF file in different domains" section.

  5. 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.

  6. Check if sample.html bundled with web-socket-js works.

  7. Make sure the port used for WebSocket (10081 in example above) is not blocked by your server/client's firewall.

  8. Install debugger version of Flash Player to see Flash errors.

  9. If you followed the steps above and you still have an issue, please report here with these information:

    • The WebSocket server library you use (e.g. em-websocket, pywebsocket) and its version
    • The Web browser you use and its version
    • The exact message you are trying to send from the server or the client
    • The result of all steps above, especially error message in step 2 if any

Supported environments

It should work on:

  • Google Chrome 4 or later, Firefox 6 or later (uses native WebSocket or MozWebSocket implementation)
  • Firefox 3 to 5, Internet Explorer 8, 9 + Flash Player 10 or later

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.

Limitations/differences compared to native WebSocket

  • You need some more lines in your JavaScript code. See "How to use it in your application" section above for details.
  • It requires Flash Player 10 or later unless the browser supports native WebSocket.
  • 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.
  • It has limited support for Cookies on WebSocket. See "Cookie support" section below for details.
  • It doesn't use proxies specified in browser config. See "Proxy support" section below for details.

Flash socket policy file

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.

If you use web-socket-ruby or 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.

If you use other Web Socket server implementation, you need to provide socket policy file yourself. See Setting up A Flash Socket Policy File for details. Implementation of socket policy file server is available at:

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.

Cookie support

web-socket-js has limited supported for Cookies on WebSocket.

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.

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.

Proxy support

The WebSocket spec specifies instructions for User Agents to support proxied connections by implementing the HTTP CONNECT method.

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.

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.

How to host HTML file and SWF file in different domains

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.

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.

  1. Unzip WebSocketMainInsecure.zip to extract WebSocketMainInsecure.swf.
  2. Put WebSocketMainInsecure.swf on your server, instead of WebSocketMain.swf.
  3. In JavaScript, set WEB_SOCKET_SWF_LOCATION to URL of your WebSocketMainInsecure.swf.

How to build WebSocketMain.swf

Install Flex 4 SDK.

$ cd flash-src
$ ./build.sh

WebSocket protocol versions

  • web-socket-js speaks WebSocket protocol defined in RFC 6455.
  • web-socket-js doesn't speak old draft versions of WebSocket protocol including hixie-76, which was supported by old version of this library. If you really need web-socket-js which speaks hixie-76, you can get it from hixie-76 branch, but the branch is no longer maintained.

License

New BSD License.

web-socket-js's People

Contributors

3rd-eden avatar abonec avatar benpickles avatar bonsaiden avatar cgbystrom avatar cope avatar doenietzomoeilijk avatar gimite avatar imanel avatar jamadden avatar jvshahid avatar kanaka avatar ken107 avatar kkirsche avatar lightsocks avatar mcav avatar rauchg avatar sleavitt avatar stefanaxelsson avatar x25 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

web-socket-js's Issues

IE9 web-socket-js only works once after each browser (re)start

[WebSocket] TypeError: Object doesn't support this property or method that's what I get. Unfortunately IE's debugger still sucks, it doesn't give me any line number, when I let it break on error, it breaks on completely random lines in different files.

Also there seem to be some more issues with 0x00 bytes, but not in every case, some work, some truncate the string.

I'm trying to figure out what's going on, but it might take some time...

EDIT:
Quick update, clearing the cache makes it work exactly one more time, after that if I don't clear the cache again it fails again with the error described above.

Why the dependence on FABridge?

I'm just wondering why we're even using FABridge in this case? I mean, we only need to expose a couple methods to JavaScript, which could easily be accomplished with just ExternalInterface, and needing to include another (unneeded) script file is kind of a bummer. Is there something FABridge gives us that I don't know about? Thanks!

wss doesn't work

Hey there! A secure connection support would be awesome, I did the homework and found http://github.com/kanaka/noVNC he has a modified version of web-socket-js but I can't get it to work,
There's no FAB init callback with https and wss. Hopefully you could do it. :)

Local Page

When web-socket-js is used one a local page (file:///home/eTM/test.js) it will not connect to a remote server.

"digest doesn't match..." error: flash socket sometimes send strange chars just after handshake

Hi,

Thanks for such a great work! Very useful!

However, I experience strange behaviours when using the flash solution (IE, FF, O).

Sometimes, just after the handshake is sent from the server, flash send first a strange string of length equals to height. And then it send a string of length equals to two containing char(255) char(255). After what, flash send the following error "digest doesn't match ...".

It's rather strange because I compute the security digest and send it when handshaking.

Any idea ?

Best regards,

Ben

Busted error handling in the SWF?

When our websocket server goes down (taking the policy file with it), subsequent connection attempts yield an Flash error, but the Flash error does not propagate down to the JS. The AS code for 'fatal' suggests that the error should propagate, but it doesn't seem to do so.

EDIT: actually, it looks as though the error handling is incomplete or a bit duplicative. The AS code has hooks in it for the various types of errors, but the errors don't fire events. Perhaps the following would work:

WAS:

private function onSocketIoError(event:IOErrorEvent):void {
  close();
  main.fatal("failed to connect Web Socket server (IoError)");
}

INSTEAD?:

private function onSocketIoError(event:IOErrorEvent):void {
  readyState = CLOSED;
  notifyStateChange();
  dispatchEvent(new Event("ioError"));
  close();
  // Necessary?
  //main.fatal("failed to connect Web Socket server (IoError)");
}

onclose() call after close() should be asynchronous

To work around the flash "recursive call" problem, WebSocket.as has the onclose event disabled in the close() call and the javascript half of the close() call does the onclose() call instead. This is fine, but it needs to be asynchronous to act more like what happens with a normal WebSockets object. The current behavior is that the onclose() method is called inline (synchronously) when the close() is called and this inconsistency make state handling more difficult.

Suggested change:

g diff include/web-socket-js/web_socket.js
diff --git a/include/web-socket-js/web_socket.js b/include/web-socket-js/web_socket.js
index ad65dd1..1f040d5 100755
--- a/include/web-socket-js/web_socket.js
+++ b/include/web-socket-js/web_socket.js
@@ -126,7 +126,11 @@
     // > You are trying to call recursively into the Flash Player which is not allowed.
     this.readyState = WebSocket.CLOSED;
     if (this.__timer) clearInterval(this.__timer);
-    if (this.onclose) this.onclose();
+    if (this.onclose) {
+        // Make it asynchronous so that it looks more like an actual
+        // close event
+        setTimeout(this.onclose, 1);
+    }
   };

   /**

The current implementation favors port 843 for socket policy files

According to this article http://www.adobe.com/devnet/flashplayer/articles/fplayer9_security.html#_Configuring_Socket_Policy:

...that you need to provide more explicit guidance to Flash Player from ActionScript by calling loadPolicyFile to indicate the location of a socket policy file. When you call loadPolicyFile rather than allowing Flash Player to check locations by default, Flash Player will wait as long as necessary for a response from a socket policy file server, rather than timing out after 3 seconds. This may help your application's reliability in marginal network conditions. It can thus be helpful to call loadPolicyFile even for a default socket policy file location—simply to request that Flash Player wait patiently for the socket policy file server to respond.

It looks like asking flash to load the policy file from port 843 (WebSocketMain.as:53) will make it favor that port over the destination port. This will cause a problem if port 843 is blocked by a firewall. I noticed that flash will try port 843 three time and it waits the first time for 3 sec then it waits for 6 sec for the second and third retries (On Windows it's 3, 6 and 12 seconds resp.) That's about 15-21 seconds between the time the user loads the page and a connection being established.

I'm proposing to remove that line (WebSocketMain.as:53) since flash will try port 843 anyway. Without that line, it'll try port 843 only once with a timeout of 3 seconds. This is more acceptable than the 15 seconds delay in my opinion.

Thanks,

Lag

Hello,

With flash socket implementation, I'm seeing significant lag for all incoming messages.
Here are timings from simple ping application. Log format is: [client start mm:ss:ms] - [client end mm:ss:ms] - [client delta] - [server msg receive date]
Native websockets in Chrome (10.0.628.0 dev):
32:11.952 - 32:11.954 - 2 - 32:11.952
32:32.464 - 32:32.466 - 2 - 32:32.466
32:46.116 - 32:46.117 - 1 - 32:46.117

Average: 1.5 ms.

Flash websocket, FF 3.6.12:
35:33.724 - 35:33.922 - 191 - 35:33.726
35:57.925 - 35:58.178 - 253 - 35:57.932
36:09.905 - 36:10.365 - 460 - 36:09.913

Flash websocket, IE 8:
37:05.725 - 37:06.185 - 460 - 37:05.727
37:20.787 - 37:21.211 - 424 - 37:20.789
37:34.220 - 37:34.736 - 516 - 37:34.225

Flash websocket, Opera 10:
39:59.038 - 39:59.165 - 127 - 39:59.047
40:11.825 - 40:12.165 - 340 - 40:11.834
40:35.937 - 40:36.165 - 228 - 40:35.946

Average is ~250 ms.

After some research I found that issue caused by following snippet of code:
// This is to avoid "You are trying to call recursively into the Flash Player ..."
// error which (I heard) happens when you pass bunch of messages.
// This workaround was written here:
// http://www.themorphicgroup.com/blog/2009/02/14/fabridge-error-you-are-trying-to-call-recursively-into-the-flash-player-which-is-not-allowed/
FABridge.EventsToCallLater["flash.events::Event"] = "true";

If you comment this line, I'm seeing ~9 ms response time in all browsers.

Question is:

  1. Is it really required?
  2. What is side effect of using it?
  3. Original link in the comment is no longer available. What is the cause of such errors?

Thanks.

Nothing works in IE6

If I try to load sample.html from Source, I've got an error in FireBug.
In console I've got an error message:

http:
[WebSocket] swfobject.embedSWF failed

It seems that SWFObject 2.2 does not work with IE6 as needed.

Firefox 3.6.13 Error #1009: Cannot access a property or method of a null object reference

Hi,

I can use the WebSocket without any problems on Chrome and IE6 (with the flash fallback), but when I try Firefox 3.6.13, it works for the first few message exchanges, but then dies during a message I send from a button onclick event. Here is the Console log (the Error #1009 shows up each time I click a button).

I've hidden the domain name, replacing everything with private.example.com because I'm not yet sure that the person I'm working on this for would be willing to expose her site to the public yet. Note that I run a policy server on port 843, the main web site is on 5004, and the web socket-enabled web server is on 8100.

[WebSocket] policy file: xmlsocket://private.example.com:843
[WebSocket] connected
[WebSocket] request header: GET /_hippie/ws/ab:16011?client_id= HTTP/1.1 Upgrade: WebSocket
Connection: Upgrade
Host: private.example.com:8100
Origin: http://private.example.com:5004
Cookie: __utma=229512961.963454258.1293130049.1295481209.1295545518.7; __utmz=229512961.1295545518.7.7.utmcsr=XXX:5004|utmccn=(referral)|utmcmd=referral|utmcct=/cgi-bin/Upcoming.cgi; COOKIE-DATA
Sec-WebSocket-Key1: 14%27=c80Z99 64
Sec-WebSocket-Key2: * 472 7o8K3 5jeE 9p bo8W *

[WebSocket] sent key3: �SOMEKEY
[WebSocket] response header:
HTTP/1.1 101 Web Socket Protocol Handshake
Upgrade: WebSocket
Connection: Upgrade
Sec-WebSocket-Origin: http://private.example.com:5004
Sec-WebSocket-Location: ws://private.example.com:8100/_hippie/ws/aucbidder:16011?client_id=

[WebSocket] reply digest: SOME-DIGEST
POST http://private.example.com:5004/cgi-bin/Upcoming.cgi
POST http://private.example.com:5004/cgi-bin/Upcoming.cgi 200 OK 4.61s lai.js (line 128)
[WebSocket] received: {"client_id":"0.83394390687782","type":"hippie.pipe.set_client_id"}
[WebSocket] sent: {"type":"watch","expanded":[],"shown":["23137","23117","23136","23119","22454","23121","23135","23122","23120","23139","23140","23141","20562","23055"]}
[WebSocket] received: {"type":"ready"}
[WebSocket] sent: {"type":"watch","expanded":["23119"],"shown":["23137","23117","23136","23119","22454","23121","23135","23122","23120","23139","23140","23141","20562","23055"]}
Error #1009: Cannot access a property or method of a null object reference.
   throw new Error(myErrorMessage[1]);   FABridge.js (line 561)
Error #1009: Cannot access a property or method of a null object reference.
   throw new Error(myErrorMessage[1]);  FABridge.js (line 561)
POST http://private.example.com:5004/cgi-bin/Upcoming.cgi 200 OK 2.01s lai.js (line 128)
POST http://private.example.com:5004/cgi-bin/Upcoming.cgi 200 OK 830ms lai.js (line 128)
Error #1009: Cannot access a property or method of a null object reference.
    throw new Error(myErrorMessage[1]);  FABridge.js (line 561)

The Flash trace log is as follows:

model: item: 0
model: item: 0
view: item: 0,undefined
view: item: 0,undefined
view: item: 0,undefined
model: item: 0
model: volume: 95
model: volume: 95
view: volume: 95,undefined
view: volume: 95,undefined
view: volume: 95,undefined
model: volume: 95
model: pause: 0
model: pause: 0
view: time: 0,0
view: time: 0,0
view: time: 0,0
view: state: 0,undefined
view: state: 0,undefined
view: state: 0,undefined
model: pause: 0

And finally, the Policy Log:

OK: Root-level SWF loaded: file:///home/michael/.mozilla/firefox/uzfwk6yl.default/extensions/[email protected]/chrome/content/flashbug/version.swf
OK: Root-level SWF loaded: http://private.example.com:8100/static/web-socket-js/WebSocketMainInsecure.swf
OK: Root-level SWF loaded: http://private.example.com/media/mediaplayer.swf
OK: Searching for  in policy files to authorize data loading from resource at xmlsocket://private.example.com:8100 by requestor from http://private.example.com:8100/static/web-socket-js/WebSocketMainInsecure.swf
OK: Policy file accepted: xmlsocket://private.example.com:843
OK: Request for resource at xmlsocket://private.example.com:8100 by requestor from http://private.example.com:8100/static/web-socket-js/WebSocketMainInsecure.swf is permitted due to policy file at xmlsocket://private.example.com:843
OK: Root-level SWF loaded: http://private.example.com:8100/static/web-socket-js/WebSocketMainInsecure.swf

I tried with both the secure and insecure versions, with no luck.

Ordinarily, I would try hunting down the misbehaving code myself, but even after following the instructions in the README.txt and rerunning build.sh, I can't seem to get any of my changes to the code to reflect in the browser. Weird.

I'd be happy to provide more details upon request,
Thanks.

close() call should call __flash.close() when CONNECTING

Right now the close() call only calls __flash.close() if readyState is OPEN. But it should really call close any time that readyState is not CLOSED or CLOSING.

The case I ran into is when I want to do the following:

  1. make a test connection
  2. tell the server to setup for a connection
  3. connect again

I call close on the test connection, but since it is ignored when CONNECTING, it eventually times out with a error. But by that time I have already issued a new connection, it causes the new connection to fail. close() should cancel CONNECTING state too.

Here is my recommended change:

--- a/web-socket-js/web_socket.js
+++ b/web-socket-js/web_socket.js
@@ -119,7 +119,10 @@
   WebSocket.prototype.close = function() {
     if (!this.__flash) return;
     this.readyState = this.__flash.getReadyState();
-    if (this.readyState != WebSocket.OPEN) return;
+    if ((this.readyState === WebSocket.CLOSED) ||
+        (this.readState === WebSocket.CLOSING)) {
+        return;
+    }
     this.__flash.close();
     // Sets/calls them manually here because Flash WebSocketConnection.close cannot fire events
     // which causes weird error:

Frames re-ordered in firefox and dropped in Opera

When using web-socket-js in firefox (3.5.3 on Linux), frames occasionally get reordered. In my test harness, I generally see the first re-ordering around frame 122 after a fresh load and every couple hundred frames after that.

Even worse, when using the same test harness in Opera (10.60), between 20-50% of all frames are simply dropped and never delivered.

My suspicion is that the problem exists at the boundary between Javascript and Flash (FABridge perhaps) and probably in the way Javascript events are being delivered.

I forked at kanaka/web-socket-js and added a test/ subdirectory that has my test harness. It's basically a html page and python script that connect to each other and send random (but checksummed) WebSocket frames back and forth at a given rate. Once you set the rate high enough (the defaults should do) you should start seeing the problem.

Opera shows dramatic slow down over time

I just pushed a WebSockets latency tester into my websockify project.

I used it to generate some performance data comparing native WebSockets and web-socket-js on various browsers.

The tests/latency.html test page send a medium size timestamped packet every 10ms to the tests/latency.py test script which simply sends it back. When the page receives the packet it
calculates the timestamp delta and updates the statistics.

As you can see between 9e76637 and 20f8374 (plus the __handleEvents patch I posted earlier), latency of web-socket-js has improved significantly for firefox 3.6.10 and firefox 4.0 beta 9 (with native WebSockets disabled).

On the other hand Opera latency started out bad and has gone to worse. The initial latency stats out better (28ms vs 290ms) but Opera's latency (in both cases) increases dramatically over time. With the more recent web-socket-js, Opera sends the first 500 packets in 13 seconds. The last 500 packets (#2500 - #3000 or so) take 72s. I see the same behavior with noVNC (performance gets worse and worse in Opera).

In both the older and newer web-socket-js Opera latency appears to be exponentially increasing over time although the newer version has a steeper angle than the older. On the other hand, the older version with Opera 10.60 seemed to get into a state where Opera would eventually lock up. I haven't see that with the newer version of web-socket-js and Opera 11.

This seems to be indicative of a memory leak somewhere. My suspicion is that this may be an Opera problem since the same web-socket-js and Flash is used with firefox and does not show the problem. But the memory leak could be in web-socket-js or the FABridge somewhere and we just see it much sooner with Opera.

Also include a cross-domain serve-able SWF.

A buddy of mine testing one of my projects sent me this email:

Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8

the error:

An ActionScript error has occurred:
SecurityError: Error #2060: Security sandbox violation: ExternalInterface caller http://engine.simplegameframework.com/lib/WebSocketMain.swf cannot access http://www.simplegameframework.com/.
    at flash.external::ExternalInterface$/_initJS()
    at flash.external::ExternalInterface$/addCallback()
    at bridge::FABridge/initializeCallbacks()
    at bridge::FABridge()
    at WebSocketMain()

I've been getting lots of similar errors to this on other sites recently.. Don't know what's up. 

I think the solution is to include Security.allowDomain("*") somewhere in the Flash code, and that will allow it to be served over distinct domains. You might want to include this hotlink-able version inside of a ZIP in the repo, otherwise there might be problems of people hotlinking to the SWF where they shouldn't be. Including it in a ZIP forces people to extract it if they really wanted to use it.

SoundManager 2 employs a similar technique, if you needed to take notes from it.

retVal variable pollutes global scope

I'm not sure if this is by design, but there's a bunch of places with retVal variable is not prefixed with var, so it ends up in global scope.

Cross-posted from Socket.IO's tracker, since it uses web-socket-js as a shim.

Simplify hasFlash()

Probably should simplify the function web_socket.js->hasFlash() by applying this code:

function hasFlash() { return swfobject.hasFlashPlayerVersion("9.0.0"); }

Problem with Firefox and IE

Hi,

I'm using websocket.js and it worked good in Chrome but in Firefox and IE, WebSocket object created but it not connected to server ...

When i start FireBug, i see some errors:

[WebSocket] cannot connect to Web Socket server at ws://localhost:12345/ (SecurityError) make sure the server is running and Flash socket policy file is correctly placed
webSocketError(Object { name="message"})web_socket.js (line 311)
[Break on this error] console.error(decodeURIComponent(message));\n

Whats the problem?

Thanks.

http-only cookies?

I'm having trouble trying to get web-socket-js to send my site's session cookie through to my server. It works in chrome, but with the flash fallback, it sends cookies I set through the javascript console, but not the session cookie. It seems to me that since some cookies are sent, it's not an 'origin' problem. Is there a way to send that session cookie as well?

New Web Sockets protocol revision 76

Hi.
Thank you for the excellent program.
Some days ago new protocol revision was accepted - http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76
Changes are very big. Mainly they are security related. Now servers and clients made on different revisons (75 or earlier and 76) can't work with each other. New versions of WebKit, Safari and Chrome use new version: http://blog.chromium.org/2010/06/websocket-protocol-updated.html

Could you implement new revision?
Thank you!

"Recursive call into Flash Player" error in Firefox

We've been getting reports of users seeing this error in Firefox:

"Error: You are trying to call recursively into the Flash Player which is not allowed. In most cases the JavaScript setTimeout function, can be used as a workaround."

uri encoded data is going out over the wire

With the latest version downloaded 18/8, I find everything is borked.

I get the following errors in Firefox 3.6.8 console:

  • [WebSocket] TypeError: WebSocket.__flash.setDebug is not a function
  • TypeError: this.__flash.readSocketData is not a function

I am also finding that uri encoded data is being sent on the wire to the WebSocket server. Although web-socket-js may need the encoding to get the data to flash, it should not be encoded when sent to the server.

If I take the call to uriEncodeComponent away then it appears to work as expected (but no response is received due to the error above).

Firefox 3.6.3 problem

  • Installed latest web-socket-ruby, started on localhost
  • copied all files in web-socket-js to /var/www/web-socket.js/, apache running on localhost
  • accessing sample.html with chromium, everything is fine
  • accessing sample.html, nothing happens
    ** webSocketContainer with swf is inserted
    ** no output on firebug console
    ** no onopen is printed

Potential changes.

Hello all,
This is my first post on this project, and I couldn't find a board or message list, so please forgive my posting as an issue. My company is currently working on a websocket implementation and we were hoping to use web-socket-js as a fallback for browsers and/or security situations that won't allow true websockets.
After reading up, testing, and scanning the source a bit I had a couple of changes I'd like to make and was wondering if anyone else has tried anything similar, or if it would be useful to post the changes once I've completed them:

  1. I'd like to replace the Vector instances with Arrays in Base64.as They aren't as fast or low-memory-footprint as primitive Vectors, but since the flash component is using Flex 3.0/3.5, it'd be nice to be able to support Flash Player 9 and those two Vector instances are the only stumbling block.
  2. I'd like to remove the dependency on FABridge and have a single flash controller responsible for managing multiple WebSocket instances rather than have javascript maintain flash instances. (This should fix that memory leak further down.)

Any feedback would be appreciated.

Sending strings with '\0' works, receiving does not

If the UTF-8 encoded data being received contains one or more '\0' (zeros), the data returned to Javascript will be truncated at the first '\0'.

This line in WebSocket.as is the culprit:
var data:String = buffer.readUTFBytes(pos - 1);

The problem is really a flash bug in that readUTFBytes treats '\0' as a string terminator even though it's legal (not a terminator) in UTF-8 encoded strings. And the real problem is that the buffer is moved ahead by the length parameter rather than by the amount actually returned. Quite aggravating.

I believe this is a working replacement for that line. However, it's so much slower it's not worth it for me to use it, but I thought I would post it in case you want the canonical version of web-socket-js to be technically correct:
var data:String = "", byte:uint;
while (buffer.bytesAvailable > 1) {
byte = buffer[buffer.position];
if (byte === 0x00) {
// readUTFBytes mishandles 0x00
data = data + "\x00";
buffer.position++;
} else if (byte === 0xff) {
// End of WebSocket frame
//ExternalInterface.call("console.log", "[WebSocket] early 0xff found");
break;
} else if ((byte & 0x80) === 0x00) {
// One UTF-8 input byte to one output byte
data = data + buffer.readUTFBytes(1);
} else {
// Assume two UTF-8 input bytes to one output byte
data = data + buffer.readUTFBytes(2);
}
}

Flash fallback doesn't work in Firefox 3.6/OS X

I've been trying to follow the instructions in README.txt to get the Flash fallback implentation of WebSockets in Firefox 3.6/OS X, but it does not appear to work. If I download web-socket-ruby and then run the echo server with

$ sudo ruby samples/echo_server.rb beebo.local 10081
Server is running at port 10081

then change sample.html WebSocket connect line to

ws = new WebSocket("ws://beebo.local:10081/");

then connections are made as expected in Chrome, and log messages on the client and server show messages being passed back and forth. However, in Firefox nothing happens. WebSocketMain.swf is loaded, but apart from that, none of the socket stuff appears to work. e.g. no attempt appears to be made to load a policy file, nothing appears on the server. I downloaded an installed the debug version of the Flash player, but that doesn't seem to to anything beyond the regular player. How can I activate "debug" mode?

called from Flash webSocketError() on server stop

When I stop server there are so error in javascript console:

[WebSocket] failed to connect Web Socket server (SecurityError) make sure the server is running and Flash socket policy file is correctly placed
webSocketError(message="%5BWebSocket%5D%20faile...is%20correctly%20placed")websoc...lash.js (line 309)
message = "%5BWebSocket%5D%20faile...is%20correctly%20placed"
websocket_flash.js (line 309)

And when I start server I must press F5 on web interface.

Flash error when server closes connection

I ran into some trouble when the server closes the connection. (I'm on firefox 3.6.3)
The closing of the connection is detected correctly and the "closed" event is fired. (including ws.onclose). But after approx 20-30 seconds, I receive a security exception, and only after this "close" is emmitted.

Firebug output:

[WebSocket] closed

[WebSocket] close

[WebSocket] failed to connect Web Socket server (SecurityError) make sure the server is running and Flash socket policy file is correctly placed

And you might want to check line 28 in web_socket.js, I'm pretty sure it should be

if (self.onclose) self.onclose();

instead of

if (self.onopen) self.onclose();

<policy-file-request/> on websocket socket

Hi
sometimes flash sent strange "policy-file-request" on websocket port. I am use tcpick for sniffing:

    # /usr/sbin/tcpick -a -C -yP "port 4005"
    11     SYN-SENT       browser:2192 > server:4005
    11     SYN-RECEIVED   browser:2192 > server:4005
    11     ESTABLISHED    browser:2192 > server:4005
    <policy-file-request/>.
    11     FIN-WAIT-1     browser:2192 > server:4005
    11     TIME-WAIT      browser:2192 > server:4005
    11     CLOSED         browser:2192 > server:4005

Flash isn't working on android devices.

Devices like HTC Hero, HTC Desire and now Nexus One(and every android 2.2 device) have flash available(ads, videos, most of flash games is working). But testing web-socket-js shows that there's some problems. I tried to check what isn't working, but no debug informations are available and server don't receive even flash policy file request.
So my request is to check what's happened or send me some info about how to debug that(both javascript and flash)

EDIT: Checked logs and all files are loaded including swf(checked on newest version)

Flash -> JS strings need to be escaped/unescaped (pull request sent)

WebSocket-JS does not work when nested/quoted JSON-like data is sent over the WebSocket, because the Flash to JS bridge doesn't properly handle that kind of data. Example:

Send this in your example echo server: {"foo": "{\"foo\": \"bar\"}"}

Expected Output: onmessage: {"foo": "{\"foo\": \"bar\"}"}
Actual Output: onmessage: null (with Firebug errors)

It throws these errors when you're logging (via webSocketLog) too.

I encountered this same issue when I made a Flash-JS bridge before switching to web-socket-js, and it happens because Flash doesn't properly handle that kind of input when passing it to Javascript. The fix I used was to escape() data as it left Flash, and unescape() it on the JS side. You'll probably need to do this with the log messages too, since they pass across the Flash->JS bridge as well and cause errors.

Let me know if that makes sense. The only complication I can see is that since you directly bind events using FABridge, you might need to wrap "onmessage", etc., so that the WebSocket Javascript class has a chance to unescape() the data coming from flash before it hits the event handlers.

_EDIT: I have sent you a pull request that fixes these issues._

\x00 in messages is not correctly handled

It seems there's something wrong with your handling of the packets, I'm using binary encoded stuff for one of my projects(http://github.com/BonsaiDen/NodeGame-Shooter) and after the first \x00 in the data the message gets terminated, even though it hasn't reached the closing \ff yet. It works fine in the native implementations.

Example of a Message:
\x00TestFoblablaFoo\x00Bla Test\xff

The expected data would be TestFoblablaFoo\x00Bla Test but actually it's TestFoblablaFoo.

cant receive unicode data

web-socket-js loses all incoming packets with unicode symbols.
if incoming data have at least one non-ascii symbol, callback onmessage()
just not be called.

tested on linux, firefox 3.6 with system locale en_US.utf8

Create an 8x8 SWF instead of 10x10?

Hi,

thanks for the library it's really useful but I always end up changing the size of the SWF from 10x10 to 8x8 so that ClickToFlash counts it as "invisible". I imagine that both of these numbers are arbitrary but it'd be nice if we could have consistency across the board.

What do you think?

Ben

Policy file should be requested form the actual websocket host, not from the server the html is hosted on

At the moment loadPolicyFile defaults to the server the HTML document is hosted on, which, like in my case, isn't the server that the actual server is running on( HTML is on Dropbox, the server is running on my local computer).

Therefore I can't connect to my server at bonsaiden.dyndns.org:28785 since flash requests the policy from dl.dropbox.com:843, which is clearly wrong.

Simple fix is to change the parameter of the initial loadPolicyFile(null) (WebSocketMain.as:54) call when creating a socket to loadPolicyFile(URLUtil.getServerName(url)), now flash correctly requests the policy from bonsaiden.dyndns.org:843 and everything works like a charm.

Memory leak in FABridge.js

As I leave my application open, the browser's memory usage grows and grows, using hundreds of MB over a few hours. I used Firebug to track this down to a memory leak in FABridge.js. The remoteInstanceCache array gets an element added to it every time a message is received from the websocket server, and is never emptied.

client sends 0xff and 0x00 at close()

I recently got web-socket-js set up and working. So far it seems to work pretty well as a drop-in replacement for standard WebSockets, so congratulations on your hard work.

I did notice that when close() is called on the client, it sends 0xff and 0x00 before terminating the connection. I looked at the draft 76 spec, and it mentions that the server is the one that should be sending this to the client, not the other way around.

Cookies not sent in handshake

This is maybe another limitation of the flash implementation, as I'm not sure if you can access the httpOnly cookies (or any of them) in a crossdomain connection.

Too bad, I was hoping to use them for identification :-)

IE Support Has Issues

Is there anything specific you have to work through for IE? I can't seem to get it to work at all, and it just shows me some cryptic error.

Bug founded in WebSocket.__addTask(function() { .__flash.addEventListener("message", function(fe) {

Bug founded in WebSocket.__addTask(function() { .__flash.addEventListener("message", function(fe) {
Bug tested opera 10.6 Beta. (thanks to developments)
Google code review: void initMessageEvent(in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg, in any dataArg, in DOMString originArg, in DOMString lastEventIdArg, in WindowProxy sourceArg, in MessagePortArray portsArg);

Fixed:
e.initMessageEvent(
// in DOMString typeArg,
"message",
// in boolean canBubbleArg
false,
// in boolean cancelableArg
false,
// in any dataArg
data,
// in DOMString originArg
null,
// in DOMString lastEventIdArg
null,
// in WindowProxy sourceArg
window, // Fixed
// in MessagePortArray portsArg
null // Fixed
);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.