websocket-transport.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. "use strict";
  5. const EventEmitter = require("devtools/shared/event-emitter");
  6. function WebSocketDebuggerTransport(socket) {
  7. EventEmitter.decorate(this);
  8. this.active = false;
  9. this.hooks = null;
  10. this.socket = socket;
  11. }
  12. WebSocketDebuggerTransport.prototype = {
  13. ready() {
  14. if (this.active) {
  15. return;
  16. }
  17. this.socket.addEventListener("message", this);
  18. this.socket.addEventListener("close", this);
  19. this.active = true;
  20. },
  21. send(object) {
  22. this.emit("send", object);
  23. if (this.socket) {
  24. this.socket.send(JSON.stringify(object));
  25. }
  26. },
  27. startBulkSend() {
  28. throw new Error("Bulk send is not supported by WebSocket transport");
  29. },
  30. close() {
  31. this.emit("close");
  32. this.active = false;
  33. this.socket.removeEventListener("message", this);
  34. this.socket.removeEventListener("close", this);
  35. this.socket.close();
  36. this.socket = null;
  37. if (this.hooks) {
  38. this.hooks.onClosed();
  39. this.hooks = null;
  40. }
  41. },
  42. handleEvent(event) {
  43. switch (event.type) {
  44. case "message":
  45. this.onMessage(event);
  46. break;
  47. case "close":
  48. this.close();
  49. break;
  50. }
  51. },
  52. onMessage({ data }) {
  53. if (typeof data !== "string") {
  54. throw new Error("Binary messages are not supported by WebSocket transport");
  55. }
  56. let object = JSON.parse(data);
  57. this.emit("packet", object);
  58. if (this.hooks) {
  59. this.hooks.onPacket(object);
  60. }
  61. },
  62. };
  63. module.exports = WebSocketDebuggerTransport;