fake.websocket.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import Base64 from '../core/base64.js';
  2. export default class FakeWebSocket {
  3. constructor(uri, protocols) {
  4. this.url = uri;
  5. this.binaryType = "arraybuffer";
  6. this.extensions = "";
  7. this.onerror = null;
  8. this.onmessage = null;
  9. this.onopen = null;
  10. if (!protocols || typeof protocols === 'string') {
  11. this.protocol = protocols;
  12. } else {
  13. this.protocol = protocols[0];
  14. }
  15. this._sendQueue = new Uint8Array(20000);
  16. this.readyState = FakeWebSocket.CONNECTING;
  17. this.bufferedAmount = 0;
  18. this._isFake = true;
  19. }
  20. close(code, reason) {
  21. this.readyState = FakeWebSocket.CLOSED;
  22. if (this.onclose) {
  23. this.onclose(new CloseEvent("close", { 'code': code, 'reason': reason, 'wasClean': true }));
  24. }
  25. }
  26. send(data) {
  27. if (this.protocol == 'base64') {
  28. data = Base64.decode(data);
  29. } else {
  30. data = new Uint8Array(data);
  31. }
  32. this._sendQueue.set(data, this.bufferedAmount);
  33. this.bufferedAmount += data.length;
  34. }
  35. _getSentData() {
  36. const res = new Uint8Array(this._sendQueue.buffer, 0, this.bufferedAmount);
  37. this.bufferedAmount = 0;
  38. return res;
  39. }
  40. _open() {
  41. this.readyState = FakeWebSocket.OPEN;
  42. if (this.onopen) {
  43. this.onopen(new Event('open'));
  44. }
  45. }
  46. _receiveData(data) {
  47. // Break apart the data to expose bugs where we assume data is
  48. // neatly packaged
  49. for (let i = 0;i < data.length;i++) {
  50. let buf = data.subarray(i, i+1);
  51. this.onmessage(new MessageEvent("message", { 'data': buf }));
  52. }
  53. }
  54. }
  55. FakeWebSocket.OPEN = WebSocket.OPEN;
  56. FakeWebSocket.CONNECTING = WebSocket.CONNECTING;
  57. FakeWebSocket.CLOSING = WebSocket.CLOSING;
  58. FakeWebSocket.CLOSED = WebSocket.CLOSED;
  59. FakeWebSocket._isFake = true;
  60. FakeWebSocket.replace = () => {
  61. if (!WebSocket._isFake) {
  62. const realVersion = WebSocket;
  63. // eslint-disable-next-line no-global-assign
  64. WebSocket = FakeWebSocket;
  65. FakeWebSocket._realVersion = realVersion;
  66. }
  67. };
  68. FakeWebSocket.restore = () => {
  69. if (WebSocket._isFake) {
  70. // eslint-disable-next-line no-global-assign
  71. WebSocket = WebSocket._realVersion;
  72. }
  73. };