fake.websocket.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. var FakeWebSocket;
  2. (function () {
  3. // PhantomJS can't create Event objects directly, so we need to use this
  4. function make_event(name, props) {
  5. var evt = document.createEvent('Event');
  6. evt.initEvent(name, true, true);
  7. if (props) {
  8. for (var prop in props) {
  9. evt[prop] = props[prop];
  10. }
  11. }
  12. return evt;
  13. }
  14. FakeWebSocket = function (uri, protocols) {
  15. this.url = uri;
  16. this.binaryType = "arraybuffer";
  17. this.extensions = "";
  18. if (!protocols || typeof protocols === 'string') {
  19. this.protocol = protocols;
  20. } else {
  21. this.protocol = protocols[0];
  22. }
  23. this._send_queue = new Uint8Array(20000);
  24. this.readyState = FakeWebSocket.CONNECTING;
  25. this.bufferedAmount = 0;
  26. this.__is_fake = true;
  27. };
  28. FakeWebSocket.prototype = {
  29. close: function (code, reason) {
  30. this.readyState = FakeWebSocket.CLOSED;
  31. if (this.onclose) {
  32. this.onclose(make_event("close", { 'code': code, 'reason': reason, 'wasClean': true }));
  33. }
  34. },
  35. send: function (data) {
  36. if (this.protocol == 'base64') {
  37. data = Base64.decode(data);
  38. } else {
  39. data = new Uint8Array(data);
  40. }
  41. this._send_queue.set(data, this.bufferedAmount);
  42. this.bufferedAmount += data.length;
  43. },
  44. _get_sent_data: function () {
  45. var res = new Uint8Array(this._send_queue.buffer, 0, this.bufferedAmount);
  46. this.bufferedAmount = 0;
  47. return res;
  48. },
  49. _open: function (data) {
  50. this.readyState = FakeWebSocket.OPEN;
  51. if (this.onopen) {
  52. this.onopen(make_event('open'));
  53. }
  54. },
  55. _receive_data: function (data) {
  56. this.onmessage(make_event("message", { 'data': data }));
  57. }
  58. };
  59. FakeWebSocket.OPEN = WebSocket.OPEN;
  60. FakeWebSocket.CONNECTING = WebSocket.CONNECTING;
  61. FakeWebSocket.CLOSING = WebSocket.CLOSING;
  62. FakeWebSocket.CLOSED = WebSocket.CLOSED;
  63. FakeWebSocket.__is_fake = true;
  64. FakeWebSocket.replace = function () {
  65. if (!WebSocket.__is_fake) {
  66. var real_version = WebSocket;
  67. WebSocket = FakeWebSocket;
  68. FakeWebSocket.__real_version = real_version;
  69. }
  70. };
  71. FakeWebSocket.restore = function () {
  72. if (WebSocket.__is_fake) {
  73. WebSocket = WebSocket.__real_version;
  74. }
  75. };
  76. })();