head_websocket.js (1774B)
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 5 "use strict"; 6 7 function WebSocketListener(closure, ws, sentMsg) { 8 this._closure = closure; 9 this._ws = ws; 10 this._sentMsg = sentMsg; 11 } 12 13 WebSocketListener.prototype = { 14 _closure: null, 15 _ws: null, 16 _sentMsg: null, 17 _received: null, 18 QueryInterface: ChromeUtils.generateQI(["nsIWebSocketListener"]), 19 20 onAcknowledge() {}, 21 onBinaryMessageAvailable(aContext, aMsg) { 22 info("WsListener::onBinaryMessageAvailable"); 23 this._received = aMsg; 24 this._ws.close(0, null); 25 }, 26 onMessageAvailable() {}, 27 onServerClose() {}, 28 onWebSocketListenerStart() {}, 29 onStart() { 30 this._ws.sendMsg(this._sentMsg); 31 }, 32 onStop(aContext, aStatusCode) { 33 try { 34 this._closure(aStatusCode, this._received); 35 this._ws = null; 36 } catch (ex) { 37 do_throw("Error in closure function: " + ex); 38 } 39 }, 40 }; 41 42 function makeWebSocketChan() { 43 let chan = Cc["@mozilla.org/network/protocol;1?name=wss"].createInstance( 44 Ci.nsIWebSocketChannel 45 ); 46 chan.initLoadInfo( 47 null, // aLoadingNode 48 Services.scriptSecurityManager.getSystemPrincipal(), 49 null, // aTriggeringPrincipal 50 Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL, 51 Ci.nsIContentPolicy.TYPE_WEBSOCKET 52 ); 53 return chan; 54 } 55 56 function openWebSocketChannelPromise(chan, url, msg) { 57 let uri = Services.io.newURI(url); 58 return new Promise(resolve => { 59 function finish(status, result) { 60 resolve([status, result]); 61 } 62 chan.asyncOpen( 63 uri, 64 url, 65 {}, 66 0, 67 new WebSocketListener(finish, chan, msg), 68 null 69 ); 70 }); 71 }