Best JavaScript code snippet using wpt
websocket.js
Source:websocket.js
1'use strict';2const EventEmitter = require('events');3const crypto = require('crypto');4const https = require('https');5const http = require('http');6const net = require('net');7const tls = require('tls');8const url = require('url');9const PerMessageDeflate = require('./permessage-deflate');10const EventTarget = require('./event-target');11const extension = require('./extension');12const Receiver = require('./receiver');13const Sender = require('./sender');14const {15 BINARY_TYPES,16 EMPTY_BUFFER,17 GUID,18 kStatusCode,19 kWebSocket,20 NOOP21} = require('./constants');22const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];23const protocolVersions = [8, 13];24const closeTimeout = 30 * 1000;25/**26 * Class representing a WebSocket.27 *28 * @extends EventEmitter29 */30class WebSocket extends EventEmitter {31 /**32 * Create a new `WebSocket`.33 *34 * @param {(String|url.Url|url.URL)} address The URL to which to connect35 * @param {(String|String[])} protocols The subprotocols36 * @param {Object} options Connection options37 */38 constructor(address, protocols, options) {39 super();40 this.readyState = WebSocket.CONNECTING;41 this.protocol = '';42 this._binaryType = BINARY_TYPES[0];43 this._closeFrameReceived = false;44 this._closeFrameSent = false;45 this._closeMessage = '';46 this._closeTimer = null;47 this._closeCode = 1006;48 this._extensions = {};49 this._receiver = null;50 this._sender = null;51 this._socket = null;52 if (address !== null) {53 this._isServer = false;54 this._redirects = 0;55 if (Array.isArray(protocols)) {56 protocols = protocols.join(', ');57 } else if (typeof protocols === 'object' && protocols !== null) {58 options = protocols;59 protocols = undefined;60 }61 initAsClient(this, address, protocols, options);62 } else {63 this._isServer = true;64 }65 }66 get CONNECTING() {67 return WebSocket.CONNECTING;68 }69 get CLOSING() {70 return WebSocket.CLOSING;71 }72 get CLOSED() {73 return WebSocket.CLOSED;74 }75 get OPEN() {76 return WebSocket.OPEN;77 }78 /**79 * This deviates from the WHATWG interface since ws doesn't support the80 * required default "blob" type (instead we define a custom "nodebuffer"81 * type).82 *83 * @type {String}84 */85 get binaryType() {86 return this._binaryType;87 }88 set binaryType(type) {89 if (!BINARY_TYPES.includes(type)) return;90 this._binaryType = type;91 //92 // Allow to change `binaryType` on the fly.93 //94 if (this._receiver) this._receiver._binaryType = type;95 }96 /**97 * @type {Number}98 */99 get bufferedAmount() {100 if (!this._socket) return 0;101 //102 // `socket.bufferSize` is `undefined` if the socket is closed.103 //104 return (this._socket.bufferSize || 0) + this._sender._bufferedBytes;105 }106 /**107 * @type {String}108 */109 get extensions() {110 return Object.keys(this._extensions).join();111 }112 /**113 * Set up the socket and the internal resources.114 *115 * @param {net.Socket} socket The network socket between the server and client116 * @param {Buffer} head The first packet of the upgraded stream117 * @param {Number} maxPayload The maximum allowed message size118 * @private119 */120 setSocket(socket, head, maxPayload) {121 const receiver = new Receiver(122 this._binaryType,123 this._extensions,124 maxPayload125 );126 this._sender = new Sender(socket, this._extensions);127 this._receiver = receiver;128 this._socket = socket;129 receiver[kWebSocket] = this;130 socket[kWebSocket] = this;131 receiver.on('conclude', receiverOnConclude);132 receiver.on('drain', receiverOnDrain);133 receiver.on('error', receiverOnError);134 receiver.on('message', receiverOnMessage);135 receiver.on('ping', receiverOnPing);136 receiver.on('pong', receiverOnPong);137 socket.setTimeout(0);138 socket.setNoDelay();139 if (head.length > 0) socket.unshift(head);140 socket.on('close', socketOnClose);141 socket.on('data', socketOnData);142 socket.on('end', socketOnEnd);143 socket.on('error', socketOnError);144 this.readyState = WebSocket.OPEN;145 this.emit('open');146 }147 /**148 * Emit the `'close'` event.149 *150 * @private151 */152 emitClose() {153 this.readyState = WebSocket.CLOSED;154 if (!this._socket) {155 this.emit('close', this._closeCode, this._closeMessage);156 return;157 }158 if (this._extensions[PerMessageDeflate.extensionName]) {159 this._extensions[PerMessageDeflate.extensionName].cleanup();160 }161 this._receiver.removeAllListeners();162 this.emit('close', this._closeCode, this._closeMessage);163 }164 /**165 * Start a closing handshake.166 *167 * +----------+ +-----------+ +----------+168 * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -169 * | +----------+ +-----------+ +----------+ |170 * +----------+ +-----------+ |171 * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING172 * +----------+ +-----------+ |173 * | | | +---+ |174 * +------------------------+-->|fin| - - - -175 * | +---+ | +---+176 * - - - - -|fin|<---------------------+177 * +---+178 *179 * @param {Number} code Status code explaining why the connection is closing180 * @param {String} data A string explaining why the connection is closing181 * @public182 */183 close(code, data) {184 if (this.readyState === WebSocket.CLOSED) return;185 if (this.readyState === WebSocket.CONNECTING) {186 const msg = 'WebSocket was closed before the connection was established';187 return abortHandshake(this, this._req, msg);188 }189 if (this.readyState === WebSocket.CLOSING) {190 if (this._closeFrameSent && this._closeFrameReceived) this._socket.end();191 return;192 }193 this.readyState = WebSocket.CLOSING;194 this._sender.close(code, data, !this._isServer, (err) => {195 //196 // This error is handled by the `'error'` listener on the socket. We only197 // want to know if the close frame has been sent here.198 //199 if (err) return;200 this._closeFrameSent = true;201 if (this._closeFrameReceived) this._socket.end();202 });203 //204 // Specify a timeout for the closing handshake to complete.205 //206 this._closeTimer = setTimeout(207 this._socket.destroy.bind(this._socket),208 closeTimeout209 );210 }211 /**212 * Send a ping.213 *214 * @param {*} data The data to send215 * @param {Boolean} mask Indicates whether or not to mask `data`216 * @param {Function} cb Callback which is executed when the ping is sent217 * @public218 */219 ping(data, mask, cb) {220 if (typeof data === 'function') {221 cb = data;222 data = mask = undefined;223 } else if (typeof mask === 'function') {224 cb = mask;225 mask = undefined;226 }227 if (this.readyState !== WebSocket.OPEN) {228 const err = new Error(229 `WebSocket is not open: readyState ${this.readyState} ` +230 `(${readyStates[this.readyState]})`231 );232 if (cb) return cb(err);233 throw err;234 }235 if (typeof data === 'number') data = data.toString();236 if (mask === undefined) mask = !this._isServer;237 this._sender.ping(data || EMPTY_BUFFER, mask, cb);238 }239 /**240 * Send a pong.241 *242 * @param {*} data The data to send243 * @param {Boolean} mask Indicates whether or not to mask `data`244 * @param {Function} cb Callback which is executed when the pong is sent245 * @public246 */247 pong(data, mask, cb) {248 if (typeof data === 'function') {249 cb = data;250 data = mask = undefined;251 } else if (typeof mask === 'function') {252 cb = mask;253 mask = undefined;254 }255 if (this.readyState !== WebSocket.OPEN) {256 const err = new Error(257 `WebSocket is not open: readyState ${this.readyState} ` +258 `(${readyStates[this.readyState]})`259 );260 if (cb) return cb(err);261 throw err;262 }263 if (typeof data === 'number') data = data.toString();264 if (mask === undefined) mask = !this._isServer;265 this._sender.pong(data || EMPTY_BUFFER, mask, cb);266 }267 /**268 * Send a data message.269 *270 * @param {*} data The message to send271 * @param {Object} options Options object272 * @param {Boolean} options.compress Specifies whether or not to compress `data`273 * @param {Boolean} options.binary Specifies whether `data` is binary or text274 * @param {Boolean} options.fin Specifies whether the fragment is the last one275 * @param {Boolean} options.mask Specifies whether or not to mask `data`276 * @param {Function} cb Callback which is executed when data is written out277 * @public278 */279 send(data, options, cb) {280 if (typeof options === 'function') {281 cb = options;282 options = {};283 }284 if (this.readyState !== WebSocket.OPEN) {285 const err = new Error(286 `WebSocket is not open: readyState ${this.readyState} ` +287 `(${readyStates[this.readyState]})`288 );289 if (cb) return cb(err);290 throw err;291 }292 if (typeof data === 'number') data = data.toString();293 const opts = Object.assign(294 {295 binary: typeof data !== 'string',296 mask: !this._isServer,297 compress: true,298 fin: true299 },300 options301 );302 if (!this._extensions[PerMessageDeflate.extensionName]) {303 opts.compress = false;304 }305 this._sender.send(data || EMPTY_BUFFER, opts, cb);306 }307 /**308 * Forcibly close the connection.309 *310 * @public311 */312 terminate() {313 if (this.readyState === WebSocket.CLOSED) return;314 if (this.readyState === WebSocket.CONNECTING) {315 const msg = 'WebSocket was closed before the connection was established';316 return abortHandshake(this, this._req, msg);317 }318 if (this._socket) {319 this.readyState = WebSocket.CLOSING;320 this._socket.destroy();321 }322 }323}324readyStates.forEach((readyState, i) => {325 WebSocket[readyState] = i;326});327//328// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.329// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface330//331['open', 'error', 'close', 'message'].forEach((method) => {332 Object.defineProperty(WebSocket.prototype, `on${method}`, {333 /**334 * Return the listener of the event.335 *336 * @return {(Function|undefined)} The event listener or `undefined`337 * @public338 */339 get() {340 const listeners = this.listeners(method);341 for (var i = 0; i < listeners.length; i++) {342 if (listeners[i]._listener) return listeners[i]._listener;343 }344 return undefined;345 },346 /**347 * Add a listener for the event.348 *349 * @param {Function} listener The listener to add350 * @public351 */352 set(listener) {353 const listeners = this.listeners(method);354 for (var i = 0; i < listeners.length; i++) {355 //356 // Remove only the listeners added via `addEventListener`.357 //358 if (listeners[i]._listener) this.removeListener(method, listeners[i]);359 }360 this.addEventListener(method, listener);361 }362 });363});364WebSocket.prototype.addEventListener = EventTarget.addEventListener;365WebSocket.prototype.removeEventListener = EventTarget.removeEventListener;366module.exports = WebSocket;367/**368 * Initialize a WebSocket client.369 *370 * @param {WebSocket} websocket The client to initialize371 * @param {(String|url.Url|url.URL)} address The URL to which to connect372 * @param {String} protocols The subprotocols373 * @param {Object} options Connection options374 * @param {(Boolean|Object)} options.perMessageDeflate Enable/disable375 * permessage-deflate376 * @param {Number} options.handshakeTimeout Timeout in milliseconds for the377 * handshake request378 * @param {Number} options.protocolVersion Value of the `Sec-WebSocket-Version`379 * header380 * @param {String} options.origin Value of the `Origin` or381 * `Sec-WebSocket-Origin` header382 * @param {Number} options.maxPayload The maximum allowed message size383 * @param {Boolean} options.followRedirects Whether or not to follow redirects384 * @param {Number} options.maxRedirects The maximum number of redirects allowed385 * @private386 */387function initAsClient(websocket, address, protocols, options) {388 const opts = Object.assign(389 {390 protocolVersion: protocolVersions[1],391 maxPayload: 100 * 1024 * 1024,392 perMessageDeflate: true,393 followRedirects: false,394 maxRedirects: 10395 },396 options,397 {398 createConnection: undefined,399 socketPath: undefined,400 hostname: undefined,401 protocol: undefined,402 timeout: undefined,403 method: undefined,404 auth: undefined,405 host: undefined,406 path: undefined,407 port: undefined408 }409 );410 if (!protocolVersions.includes(opts.protocolVersion)) {411 throw new RangeError(412 `Unsupported protocol version: ${opts.protocolVersion} ` +413 `(supported versions: ${protocolVersions.join(', ')})`414 );415 }416 var parsedUrl;417 if (typeof address === 'object' && address.href !== undefined) {418 parsedUrl = address;419 websocket.url = address.href;420 } else {421 //422 // The WHATWG URL constructor is not available on Node.js < 6.13.0423 //424 parsedUrl = url.URL ? new url.URL(address) : url.parse(address);425 websocket.url = address;426 }427 const isUnixSocket = parsedUrl.protocol === 'ws+unix:';428 if (!parsedUrl.host && (!isUnixSocket || !parsedUrl.pathname)) {429 throw new Error(`Invalid URL: ${websocket.url}`);430 }431 const isSecure =432 parsedUrl.protocol === 'wss:' || parsedUrl.protocol === 'https:';433 const defaultPort = isSecure ? 443 : 80;434 const key = crypto.randomBytes(16).toString('base64');435 const get = isSecure ? https.get : http.get;436 const path = parsedUrl.search437 ? `${parsedUrl.pathname || '/'}${parsedUrl.search}`438 : parsedUrl.pathname || '/';439 var perMessageDeflate;440 opts.createConnection = isSecure ? tlsConnect : netConnect;441 opts.defaultPort = opts.defaultPort || defaultPort;442 opts.port = parsedUrl.port || defaultPort;443 opts.host = parsedUrl.hostname.startsWith('[')444 ? parsedUrl.hostname.slice(1, -1)445 : parsedUrl.hostname;446 opts.headers = Object.assign(447 {448 'Sec-WebSocket-Version': opts.protocolVersion,449 'Sec-WebSocket-Key': key,450 Connection: 'Upgrade',451 Upgrade: 'websocket'452 },453 opts.headers454 );455 opts.path = path;456 opts.timeout = opts.handshakeTimeout;457 if (opts.perMessageDeflate) {458 perMessageDeflate = new PerMessageDeflate(459 opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},460 false,461 opts.maxPayload462 );463 opts.headers['Sec-WebSocket-Extensions'] = extension.format({464 [PerMessageDeflate.extensionName]: perMessageDeflate.offer()465 });466 }467 if (protocols) {468 opts.headers['Sec-WebSocket-Protocol'] = protocols;469 }470 if (opts.origin) {471 if (opts.protocolVersion < 13) {472 opts.headers['Sec-WebSocket-Origin'] = opts.origin;473 } else {474 opts.headers.Origin = opts.origin;475 }476 }477 if (parsedUrl.auth) {478 opts.auth = parsedUrl.auth;479 } else if (parsedUrl.username || parsedUrl.password) {480 opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;481 }482 if (isUnixSocket) {483 const parts = path.split(':');484 opts.socketPath = parts[0];485 opts.path = parts[1];486 }487 var req = (websocket._req = get(opts));488 if (opts.timeout) {489 req.on('timeout', () => {490 abortHandshake(websocket, req, 'Opening handshake has timed out');491 });492 }493 req.on('error', (err) => {494 if (websocket._req.aborted) return;495 req = websocket._req = null;496 websocket.readyState = WebSocket.CLOSING;497 websocket.emit('error', err);498 websocket.emitClose();499 });500 req.on('response', (res) => {501 const location = res.headers.location;502 const statusCode = res.statusCode;503 if (504 location &&505 opts.followRedirects &&506 statusCode >= 300 &&507 statusCode < 400508 ) {509 if (++websocket._redirects > opts.maxRedirects) {510 abortHandshake(websocket, req, 'Maximum redirects exceeded');511 return;512 }513 req.abort();514 const addr = url.URL515 ? new url.URL(location, address)516 : url.resolve(address, location);517 initAsClient(websocket, addr, protocols, options);518 } else if (!websocket.emit('unexpected-response', req, res)) {519 abortHandshake(520 websocket,521 req,522 `Unexpected server response: ${res.statusCode}`523 );524 }525 });526 req.on('upgrade', (res, socket, head) => {527 websocket.emit('upgrade', res);528 //529 // The user may have closed the connection from a listener of the `upgrade`530 // event.531 //532 if (websocket.readyState !== WebSocket.CONNECTING) return;533 req = websocket._req = null;534 const digest = crypto535 .createHash('sha1')536 .update(key + GUID)537 .digest('base64');538 if (res.headers['sec-websocket-accept'] !== digest) {539 abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header');540 return;541 }542 const serverProt = res.headers['sec-websocket-protocol'];543 const protList = (protocols || '').split(/, */);544 var protError;545 if (!protocols && serverProt) {546 protError = 'Server sent a subprotocol but none was requested';547 } else if (protocols && !serverProt) {548 protError = 'Server sent no subprotocol';549 } else if (serverProt && !protList.includes(serverProt)) {550 protError = 'Server sent an invalid subprotocol';551 }552 if (protError) {553 abortHandshake(websocket, socket, protError);554 return;555 }556 if (serverProt) websocket.protocol = serverProt;557 if (perMessageDeflate) {558 try {559 const extensions = extension.parse(560 res.headers['sec-websocket-extensions']561 );562 if (extensions[PerMessageDeflate.extensionName]) {563 perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);564 websocket._extensions[565 PerMessageDeflate.extensionName566 ] = perMessageDeflate;567 }568 } catch (err) {569 abortHandshake(570 websocket,571 socket,572 'Invalid Sec-WebSocket-Extensions header'573 );574 return;575 }576 }577 websocket.setSocket(socket, head, opts.maxPayload);578 });579}580/**581 * Create a `net.Socket` and initiate a connection.582 *583 * @param {Object} options Connection options584 * @return {net.Socket} The newly created socket used to start the connection585 * @private586 */587function netConnect(options) {588 //589 // Override `options.path` only if `options` is a copy of the original options590 // object. This is always true on Node.js >= 8 but not on Node.js 6 where591 // `options.socketPath` might be `undefined` even if the `socketPath` option592 // was originally set.593 //594 if (options.protocolVersion) options.path = options.socketPath;595 return net.connect(options);596}597/**598 * Create a `tls.TLSSocket` and initiate a connection.599 *600 * @param {Object} options Connection options601 * @return {tls.TLSSocket} The newly created socket used to start the connection602 * @private603 */604function tlsConnect(options) {605 options.path = undefined;606 options.servername = options.servername || options.host;607 return tls.connect(options);608}609/**610 * Abort the handshake and emit an error.611 *612 * @param {WebSocket} websocket The WebSocket instance613 * @param {(http.ClientRequest|net.Socket)} stream The request to abort or the614 * socket to destroy615 * @param {String} message The error message616 * @private617 */618function abortHandshake(websocket, stream, message) {619 websocket.readyState = WebSocket.CLOSING;620 const err = new Error(message);621 Error.captureStackTrace(err, abortHandshake);622 if (stream.setHeader) {623 stream.abort();624 stream.once('abort', websocket.emitClose.bind(websocket));625 websocket.emit('error', err);626 } else {627 stream.destroy(err);628 stream.once('error', websocket.emit.bind(websocket, 'error'));629 stream.once('close', websocket.emitClose.bind(websocket));630 }631}632/**633 * The listener of the `Receiver` `'conclude'` event.634 *635 * @param {Number} code The status code636 * @param {String} reason The reason for closing637 * @private638 */639function receiverOnConclude(code, reason) {640 const websocket = this[kWebSocket];641 websocket._socket.removeListener('data', socketOnData);642 websocket._socket.resume();643 websocket._closeFrameReceived = true;644 websocket._closeMessage = reason;645 websocket._closeCode = code;646 if (code === 1005) websocket.close();647 else websocket.close(code, reason);648}649/**650 * The listener of the `Receiver` `'drain'` event.651 *652 * @private653 */654function receiverOnDrain() {655 this[kWebSocket]._socket.resume();656}657/**658 * The listener of the `Receiver` `'error'` event.659 *660 * @param {(RangeError|Error)} err The emitted error661 * @private662 */663function receiverOnError(err) {664 const websocket = this[kWebSocket];665 websocket._socket.removeListener('data', socketOnData);666 websocket.readyState = WebSocket.CLOSING;667 websocket._closeCode = err[kStatusCode];668 websocket.emit('error', err);669 websocket._socket.destroy();670}671/**672 * The listener of the `Receiver` `'finish'` event.673 *674 * @private675 */676function receiverOnFinish() {677 this[kWebSocket].emitClose();678}679/**680 * The listener of the `Receiver` `'message'` event.681 *682 * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The message683 * @private684 */685function receiverOnMessage(data) {686 this[kWebSocket].emit('message', data);687}688/**689 * The listener of the `Receiver` `'ping'` event.690 *691 * @param {Buffer} data The data included in the ping frame692 * @private693 */694function receiverOnPing(data) {695 const websocket = this[kWebSocket];696 websocket.pong(data, !websocket._isServer, NOOP);697 websocket.emit('ping', data);698}699/**700 * The listener of the `Receiver` `'pong'` event.701 *702 * @param {Buffer} data The data included in the pong frame703 * @private704 */705function receiverOnPong(data) {706 this[kWebSocket].emit('pong', data);707}708/**709 * The listener of the `net.Socket` `'close'` event.710 *711 * @private712 */713function socketOnClose() {714 const websocket = this[kWebSocket];715 this.removeListener('close', socketOnClose);716 this.removeListener('end', socketOnEnd);717 websocket.readyState = WebSocket.CLOSING;718 //719 // The close frame might not have been received or the `'end'` event emitted,720 // for example, if the socket was destroyed due to an error. Ensure that the721 // `receiver` stream is closed after writing any remaining buffered data to722 // it. If the readable side of the socket is in flowing mode then there is no723 // buffered data as everything has been already written and `readable.read()`724 // will return `null`. If instead, the socket is paused, any possible buffered725 // data will be read as a single chunk and emitted synchronously in a single726 // `'data'` event.727 //728 websocket._socket.read();729 websocket._receiver.end();730 this.removeListener('data', socketOnData);731 this[kWebSocket] = undefined;732 clearTimeout(websocket._closeTimer);733 if (734 websocket._receiver._writableState.finished ||735 websocket._receiver._writableState.errorEmitted736 ) {737 websocket.emitClose();738 } else {739 websocket._receiver.on('error', receiverOnFinish);740 websocket._receiver.on('finish', receiverOnFinish);741 }742}743/**744 * The listener of the `net.Socket` `'data'` event.745 *746 * @param {Buffer} chunk A chunk of data747 * @private748 */749function socketOnData(chunk) {750 if (!this[kWebSocket]._receiver.write(chunk)) {751 this.pause();752 }753}754/**755 * The listener of the `net.Socket` `'end'` event.756 *757 * @private758 */759function socketOnEnd() {760 const websocket = this[kWebSocket];761 websocket.readyState = WebSocket.CLOSING;762 websocket._receiver.end();763 this.end();764}765/**766 * The listener of the `net.Socket` `'error'` event.767 *768 * @private769 */770function socketOnError() {771 const websocket = this[kWebSocket];772 this.removeListener('error', socketOnError);773 this.on('error', NOOP);774 websocket.readyState = WebSocket.CLOSING;775 this.destroy();...
web_socket.js
Source:web_socket.js
1// Copyright: Hiroshi Ichikawa <http://gimite.net/en/>2// License: New BSD License3// Reference: http://dev.w3.org/html5/websockets/4// Reference: http://tools.ietf.org/html/rfc64555(function() {6 7 if (window.WEB_SOCKET_FORCE_FLASH) {8 // Keeps going.9 } else if (window.WebSocket) {10 return;11 } else if (window.MozWebSocket) {12 // Firefox.13 window.WebSocket = MozWebSocket;14 return;15 }16 17 var logger;18 if (window.WEB_SOCKET_LOGGER) {19 logger = WEB_SOCKET_LOGGER;20 } else if (window.console && window.console.log && window.console.error) {21 // In some environment, console is defined but console.log or console.error is missing.22 logger = window.console;23 } else {24 logger = {log: function(){ }, error: function(){ }};25 }26 27 // swfobject.hasFlashPlayerVersion("10.0.0") doesn't work with Gnash.28 if (swfobject.getFlashPlayerVersion().major < 10) {29 logger.error("Flash Player >= 10.0.0 is required.");30 return;31 }32 if (location.protocol == "file:") {33 logger.error(34 "WARNING: web-socket-js doesn't work in file:///... URL " +35 "unless you set Flash Security Settings properly. " +36 "Open the page via Web server i.e. http://...");37 }38 /**39 * Our own implementation of WebSocket class using Flash.40 * @param {string} url41 * @param {array or string} protocols42 * @param {string} proxyHost43 * @param {int} proxyPort44 * @param {string} headers45 */46 window.WebSocket = function(url, protocols, proxyHost, proxyPort, headers) {47 var self = this;48 self.__id = WebSocket.__nextId++;49 WebSocket.__instances[self.__id] = self;50 self.readyState = WebSocket.CONNECTING;51 self.bufferedAmount = 0;52 self.__events = {};53 if (!protocols) {54 protocols = [];55 } else if (typeof protocols == "string") {56 protocols = [protocols];57 }58 // Uses setTimeout() to make sure __createFlash() runs after the caller sets ws.onopen etc.59 // Otherwise, when onopen fires immediately, onopen is called before it is set.60 self.__createTask = setTimeout(function() {61 WebSocket.__addTask(function() {62 self.__createTask = null;63 WebSocket.__flash.create(64 self.__id, url, protocols, proxyHost || null, proxyPort || 0, headers || null);65 });66 }, 0);67 };68 /**69 * Send data to the web socket.70 * @param {string} data The data to send to the socket.71 * @return {boolean} True for success, false for failure.72 */73 WebSocket.prototype.send = function(data) {74 if (this.readyState == WebSocket.CONNECTING) {75 throw "INVALID_STATE_ERR: Web Socket connection has not been established";76 }77 // We use encodeURIComponent() here, because FABridge doesn't work if78 // the argument includes some characters. We don't use escape() here79 // because of this:80 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#escape_and_unescape_Functions81 // But it looks decodeURIComponent(encodeURIComponent(s)) doesn't82 // preserve all Unicode characters either e.g. "\uffff" in Firefox.83 // Note by wtritch: Hopefully this will not be necessary using ExternalInterface. Will require84 // additional testing.85 var result = WebSocket.__flash.send(this.__id, encodeURIComponent(data));86 if (result < 0) { // success87 return true;88 } else {89 this.bufferedAmount += result;90 return false;91 }92 };93 /**94 * Close this web socket gracefully.95 */96 WebSocket.prototype.close = function() {97 if (this.__createTask) {98 clearTimeout(this.__createTask);99 this.__createTask = null;100 this.readyState = WebSocket.CLOSED;101 return;102 }103 if (this.readyState == WebSocket.CLOSED || this.readyState == WebSocket.CLOSING) {104 return;105 }106 this.readyState = WebSocket.CLOSING;107 WebSocket.__flash.close(this.__id);108 };109 /**110 * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}111 *112 * @param {string} type113 * @param {function} listener114 * @param {boolean} useCapture115 * @return void116 */117 WebSocket.prototype.addEventListener = function(type, listener, useCapture) {118 if (!(type in this.__events)) {119 this.__events[type] = [];120 }121 this.__events[type].push(listener);122 };123 /**124 * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}125 *126 * @param {string} type127 * @param {function} listener128 * @param {boolean} useCapture129 * @return void130 */131 WebSocket.prototype.removeEventListener = function(type, listener, useCapture) {132 if (!(type in this.__events)) return;133 var events = this.__events[type];134 for (var i = events.length - 1; i >= 0; --i) {135 if (events[i] === listener) {136 events.splice(i, 1);137 break;138 }139 }140 };141 /**142 * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}143 *144 * @param {Event} event145 * @return void146 */147 WebSocket.prototype.dispatchEvent = function(event) {148 var events = this.__events[event.type] || [];149 for (var i = 0; i < events.length; ++i) {150 events[i](event);151 }152 var handler = this["on" + event.type];153 if (handler) handler.apply(this, [event]);154 };155 /**156 * Handles an event from Flash.157 * @param {Object} flashEvent158 */159 WebSocket.prototype.__handleEvent = function(flashEvent) {160 161 if ("readyState" in flashEvent) {162 this.readyState = flashEvent.readyState;163 }164 if ("protocol" in flashEvent) {165 this.protocol = flashEvent.protocol;166 }167 168 var jsEvent;169 if (flashEvent.type == "open" || flashEvent.type == "error") {170 jsEvent = this.__createSimpleEvent(flashEvent.type);171 } else if (flashEvent.type == "close") {172 jsEvent = this.__createSimpleEvent("close");173 jsEvent.wasClean = flashEvent.wasClean ? true : false;174 jsEvent.code = flashEvent.code;175 jsEvent.reason = flashEvent.reason;176 } else if (flashEvent.type == "message") {177 var data = decodeURIComponent(flashEvent.message);178 jsEvent = this.__createMessageEvent("message", data);179 } else {180 throw "unknown event type: " + flashEvent.type;181 }182 183 this.dispatchEvent(jsEvent);184 185 };186 187 WebSocket.prototype.__createSimpleEvent = function(type) {188 if (document.createEvent && window.Event) {189 var event = document.createEvent("Event");190 event.initEvent(type, false, false);191 return event;192 } else {193 return {type: type, bubbles: false, cancelable: false};194 }195 };196 197 WebSocket.prototype.__createMessageEvent = function(type, data) {198 if (window.MessageEvent && typeof(MessageEvent) == "function" && !window.opera) {199 return new MessageEvent("message", {200 "view": window,201 "bubbles": false,202 "cancelable": false,203 "data": data204 });205 } else if (document.createEvent && window.MessageEvent && !window.opera) {206 var event = document.createEvent("MessageEvent");207 event.initMessageEvent("message", false, false, data, null, null, window, null);208 return event;209 } else {210 // Old IE and Opera, the latter one truncates the data parameter after any 0x00 bytes.211 return {type: type, data: data, bubbles: false, cancelable: false};212 }213 };214 215 /**216 * Define the WebSocket readyState enumeration.217 */218 WebSocket.CONNECTING = 0;219 WebSocket.OPEN = 1;220 WebSocket.CLOSING = 2;221 WebSocket.CLOSED = 3;222 // Field to check implementation of WebSocket.223 WebSocket.__isFlashImplementation = true;224 WebSocket.__initialized = false;225 WebSocket.__flash = null;226 WebSocket.__instances = {};227 WebSocket.__tasks = [];228 WebSocket.__nextId = 0;229 230 /**231 * Load a new flash security policy file.232 * @param {string} url233 */234 WebSocket.loadFlashPolicyFile = function(url){235 WebSocket.__addTask(function() {236 WebSocket.__flash.loadManualPolicyFile(url);237 });238 };239 /**240 * Loads WebSocketMain.swf and creates WebSocketMain object in Flash.241 */242 WebSocket.__initialize = function() {243 244 if (WebSocket.__initialized) return;245 WebSocket.__initialized = true;246 247 if (WebSocket.__swfLocation) {248 // For backword compatibility.249 window.WEB_SOCKET_SWF_LOCATION = WebSocket.__swfLocation;250 }251 if (!window.WEB_SOCKET_SWF_LOCATION) {252 logger.error("[WebSocket] set WEB_SOCKET_SWF_LOCATION to location of WebSocketMain.swf");253 return;254 }255 if (!window.WEB_SOCKET_SUPPRESS_CROSS_DOMAIN_SWF_ERROR &&256 !WEB_SOCKET_SWF_LOCATION.match(/(^|\/)WebSocketMainInsecure\.swf(\?.*)?$/) &&257 WEB_SOCKET_SWF_LOCATION.match(/^\w+:\/\/([^\/]+)/)) {258 var swfHost = RegExp.$1;259 if (location.host != swfHost) {260 logger.error(261 "[WebSocket] You must host HTML and WebSocketMain.swf in the same host " +262 "('" + location.host + "' != '" + swfHost + "'). " +263 "See also 'How to host HTML file and SWF file in different domains' section " +264 "in README.md. If you use WebSocketMainInsecure.swf, you can suppress this message " +265 "by WEB_SOCKET_SUPPRESS_CROSS_DOMAIN_SWF_ERROR = true;");266 }267 }268 var container = document.createElement("div");269 container.id = "webSocketContainer";270 // Hides Flash box. We cannot use display: none or visibility: hidden because it prevents271 // Flash from loading at least in IE. So we move it out of the screen at (-100, -100).272 // But this even doesn't work with Flash Lite (e.g. in Droid Incredible). So with Flash273 // Lite, we put it at (0, 0). This shows 1x1 box visible at left-top corner but this is274 // the best we can do as far as we know now.275 container.style.position = "absolute";276 if (WebSocket.__isFlashLite()) {277 container.style.left = "0px";278 container.style.top = "0px";279 } else {280 container.style.left = "-100px";281 container.style.top = "-100px";282 }283 var holder = document.createElement("div");284 holder.id = "webSocketFlash";285 container.appendChild(holder);286 document.body.appendChild(container);287 // See this article for hasPriority:288 // http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html289 swfobject.embedSWF(290 WEB_SOCKET_SWF_LOCATION,291 "webSocketFlash",292 "1" /* width */,293 "1" /* height */,294 "10.0.0" /* SWF version */,295 null,296 null,297 {hasPriority: true, swliveconnect : true, allowScriptAccess: "always"},298 null,299 function(e) {300 if (!e.success) {301 logger.error("[WebSocket] swfobject.embedSWF failed");302 }303 }304 );305 306 };307 308 /**309 * Called by Flash to notify JS that it's fully loaded and ready310 * for communication.311 */312 WebSocket.__onFlashInitialized = function() {313 // We need to set a timeout here to avoid round-trip calls314 // to flash during the initialization process.315 setTimeout(function() {316 WebSocket.__flash = document.getElementById("webSocketFlash");317 WebSocket.__flash.setCallerUrl(location.href);318 WebSocket.__flash.setDebug(!!window.WEB_SOCKET_DEBUG);319 for (var i = 0; i < WebSocket.__tasks.length; ++i) {320 WebSocket.__tasks[i]();321 }322 WebSocket.__tasks = [];323 }, 0);324 };325 326 /**327 * Called by Flash to notify WebSockets events are fired.328 */329 WebSocket.__onFlashEvent = function() {330 setTimeout(function() {331 try {332 // Gets events using receiveEvents() instead of getting it from event object333 // of Flash event. This is to make sure to keep message order.334 // It seems sometimes Flash events don't arrive in the same order as they are sent.335 var events = WebSocket.__flash.receiveEvents();336 for (var i = 0; i < events.length; ++i) {337 WebSocket.__instances[events[i].webSocketId].__handleEvent(events[i]);338 }339 } catch (e) {340 logger.error(e);341 }342 }, 0);343 return true;344 };345 346 // Called by Flash.347 WebSocket.__log = function(message) {348 logger.log(decodeURIComponent(message));349 };350 351 // Called by Flash.352 WebSocket.__error = function(message) {353 logger.error(decodeURIComponent(message));354 };355 356 WebSocket.__addTask = function(task) {357 if (WebSocket.__flash) {358 task();359 } else {360 WebSocket.__tasks.push(task);361 }362 };363 364 /**365 * Test if the browser is running flash lite.366 * @return {boolean} True if flash lite is running, false otherwise.367 */368 WebSocket.__isFlashLite = function() {369 if (!window.navigator || !window.navigator.mimeTypes) {370 return false;371 }372 var mimeType = window.navigator.mimeTypes["application/x-shockwave-flash"];373 if (!mimeType || !mimeType.enabledPlugin || !mimeType.enabledPlugin.filename) {374 return false;375 }376 return mimeType.enabledPlugin.filename.match(/flashlite/i) ? true : false;377 };378 379 if (!window.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION) {380 // NOTE:381 // This fires immediately if web_socket.js is dynamically loaded after382 // the document is loaded.383 swfobject.addDomLoadEvent(function() {384 WebSocket.__initialize();385 });386 }387 ...
Using AI Code Generation
1var WebSocketClient = require('websocket').client;2var client = new WebSocketClient();3var request = require('request');4var fs = require('fs');5var parseString = require('xml2js').parseString;6var async = require('async');7var url = require('url');8var path = require('path');9var util = require('util');10var exec = require('child_process').exec;11var config = require('./config.json');12var wptHost = config.wptHost;13var wptKey = config.wptKey;14var wptLocation = config.wptLocation;15var wptRuns = config.wptRuns;16var wptConnectivity = config.wptConnectivity;17var wptVideo = config.wptVideo;18var wptVideoCapture = config.wptVideoCapture;19var wptVideoFullResolution = config.wptVideoFullResolution;20var wptVideoTimeLimit = config.wptVideoTimeLimit;21var wptVideoFrameRate = config.wptVideoFrameRate;22var wptVideoCodec = config.wptVideoCodec;23var wptVideoBitrate = config.wptVideoBitrate;24var wptVideoBufferSize = config.wptVideoBufferSize;25var wptVideoThreads = config.wptVideoThreads;26var wptVideoRenderThreads = config.wptVideoRenderThreads;27var wptVideoQuality = config.wptVideoQuality;28var wptVideoFps = config.wptVideoFps;29var wptVideoCodec = config.wptVideoCodec;30var wptVideoBitrate = config.wptVideoBitrate;31var wptVideoBufferSize = config.wptVideoBufferSize;32var wptVideoThreads = config.wptVideoThreads;33var wptVideoRenderThreads = config.wptVideoRenderThreads;34var wptVideoQuality = config.wptVideoQuality;35var wptVideoFps = config.wptVideoFps;36var wptVideoCodec = config.wptVideoCodec;37var wptVideoBitrate = config.wptVideoBitrate;38var wptVideoBufferSize = config.wptVideoBufferSize;39var wptVideoThreads = config.wptVideoThreads;40var wptVideoRenderThreads = config.wptVideoRenderThreads;41var wptVideoQuality = config.wptVideoQuality;42var wptVideoFps = config.wptVideoFps;43var wptVideoCodec = config.wptVideoCodec;
Using AI Code Generation
1var wpt = require('webpagetest');2var fs = require('fs');3var path = require('path');4var csv = require('fast-csv');5var csvStream = csv.createWriteStream({headers: true}),6 writableStream = fs.createWriteStream("output.csv");7var csvStream1 = csv.createWriteStream({headers: true}),8 writableStream1 = fs.createWriteStream("output1.csv");9var csvStream2 = csv.createWriteStream({headers: true}),10 writableStream2 = fs.createWriteStream("output2.csv");11var csvStream3 = csv.createWriteStream({headers: true}),12 writableStream3 = fs.createWriteStream("output3.csv");13var csvStream4 = csv.createWriteStream({headers: true}),14 writableStream4 = fs.createWriteStream("output4.csv");15var csvStream5 = csv.createWriteStream({headers: true}),16 writableStream5 = fs.createWriteStream("output5.csv");17var csvStream6 = csv.createWriteStream({headers: true}),18 writableStream6 = fs.createWriteStream("output6.csv");19var csvStream7 = csv.createWriteStream({headers: true}),20 writableStream7 = fs.createWriteStream("output7.csv");21var csvStream8 = csv.createWriteStream({headers: true}),22 writableStream8 = fs.createWriteStream("output8.csv");23var csvStream9 = csv.createWriteStream({headers: true}),24 writableStream9 = fs.createWriteStream("output9.csv");25var csvStream10 = csv.createWriteStream({headers: true}),26 writableStream10 = fs.createWriteStream("output10.csv");27var csvStream11 = csv.createWriteStream({headers: true}),28 writableStream11 = fs.createWriteStream("output11.csv");29var csvStream12 = csv.createWriteStream({headers: true}),30 writableStream12 = fs.createWriteStream("output12.csv");31var csvStream13 = csv.createWriteStream({headers: true}),32 writableStream13 = fs.createWriteStream("output13.csv");33var csvStream14 = csv.createWriteStream({headers: true}),34 writableStream14 = fs.createWriteStream("output14.csv");35var csvStream15 = csv.createWriteStream({headers: true}),36 writableStream15 = fs.createWriteStream("output15.csv");
Using AI Code Generation
1var Wpt = require('wpt-api');2var wpt = new Wpt('A.2c2e8c7a3f3a3b7e2a2d8b0f3c4f4a4c');3var fs = require('fs');4var url = 'www.google.com';5var options = {6 videoParams: {7 }8};9var test = wpt.runTest(url, options, function (err, data) {10 if (err) {11 console.log(err);12 }13 fs.writeFile('test.json', JSON.stringify(data), function (err) {14 if (err) {15 return console.log(err);16 }17 console.log('The file was saved!');18 });19});
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!