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/. */
5 // This is an XPCOM service-ified copy of ../devtools/shared/transport/websocket-transport.js.
9 ChromeUtils.defineESModuleGetters(lazy, {
10 EventEmitter: "resource://gre/modules/EventEmitter.sys.mjs",
13 export function WebSocketTransport(socket) {
14 lazy.EventEmitter.decorate(this);
21 WebSocketTransport.prototype = {
27 this.socket.addEventListener("message", this);
28 this.socket.addEventListener("close", this);
34 this.emit("send", object);
36 this.socket.send(JSON.stringify(object));
41 throw new Error("Bulk send is not supported by WebSocket transport");
45 * Force closing the active connection and WebSocket.
54 this.hooks.onConnectionClose();
59 this.socket.removeEventListener("message", this);
61 // Remove the listener that is used when the connection
62 // is closed because we already emitted the 'close' event.
63 // Instead listen for the closing of the WebSocket.
64 this.socket.removeEventListener("close", this);
65 this.socket.addEventListener("close", this.onSocketClose.bind(this));
67 // Close socket with code `1000` for a normal closure.
68 this.socket.close(1000);
72 * Callback for socket on close event,
73 * it is used in case websocket was closed by the client.
82 this.hooks.onConnectionClose();
83 this.hooks.onSocketClose();
89 this.socket.removeEventListener("message", this);
90 this.socket.removeEventListener("close", this);
95 * Callback which is called when we can be sure that websocket is closed.
101 this.hooks.onSocketClose();
107 switch (event.type) {
109 this.onMessage(event);
117 onMessage({ data }) {
118 if (typeof data !== "string") {
120 "Binary messages are not supported by WebSocket transport"
124 const object = JSON.parse(data);
125 this.emit("packet", object);
127 this.hooks.onPacket(object);