WebSocketMain.as 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright: Hiroshi Ichikawa <http://gimite.net/en/>
  2. // Lincense: New BSD Lincense
  3. // Reference: http://dev.w3.org/html5/websockets/
  4. // Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-31
  5. package {
  6. import flash.display.*;
  7. import flash.events.*;
  8. import flash.external.*;
  9. import flash.net.*;
  10. import flash.system.*;
  11. import flash.utils.*;
  12. import mx.core.*;
  13. import mx.controls.*;
  14. import mx.events.*;
  15. import mx.utils.*;
  16. import bridge.FABridge;
  17. public class WebSocketMain extends Sprite {
  18. private var policyLoaded:Boolean = false;
  19. private var callerUrl:String;
  20. public function WebSocketMain() {
  21. // This is to avoid "You are trying to call recursively into the Flash Player ..."
  22. // error which (I heard) happens when you pass bunch of messages.
  23. // This workaround was written here:
  24. // http://www.themorphicgroup.com/blog/2009/02/14/fabridge-error-you-are-trying-to-call-recursively-into-the-flash-player-which-is-not-allowed/
  25. FABridge.EventsToCallLater["flash.events::Event"] = "true";
  26. FABridge.EventsToCallLater["WebSocketMessageEvent"] = "true";
  27. FABridge.EventsToCallLater["WebSocketStateEvent"] = "true";
  28. var fab:FABridge = new FABridge();
  29. fab.rootObject = this;
  30. //log("Flash initialized");
  31. }
  32. public function setCallerUrl(url:String):void {
  33. callerUrl = url;
  34. }
  35. public function create(
  36. url:String, protocol:String,
  37. proxyHost:String = null, proxyPort:int = 0,
  38. headers:String = null):WebSocket {
  39. loadPolicyFile(null);
  40. return new WebSocket(this, url, protocol, proxyHost, proxyPort, headers);
  41. }
  42. public function getOrigin():String {
  43. return (URLUtil.getProtocol(this.callerUrl) + "://" +
  44. URLUtil.getServerNameWithPort(this.callerUrl)).toLowerCase();
  45. }
  46. public function getCallerHost():String {
  47. return URLUtil.getServerName(this.callerUrl);
  48. }
  49. public function loadPolicyFile(url:String):void {
  50. if (policyLoaded && !url) return;
  51. if (!url) {
  52. url = "xmlsocket://" + URLUtil.getServerName(this.callerUrl) + ":843";
  53. }
  54. log("policy file: " + url);
  55. Security.loadPolicyFile(url);
  56. policyLoaded = true;
  57. }
  58. public function log(message:String):void {
  59. ExternalInterface.call("webSocketLog", encodeURIComponent("[WebSocket] " + message));
  60. }
  61. public function fatal(message:String):void {
  62. ExternalInterface.call("webSocketError", encodeURIComponent("[WebSocket] " + message));
  63. throw message;
  64. }
  65. }
  66. }