JAVASCRIPT   8

api.js

Guest on 21st May 2021 06:42:29 AM

  1. var EventTarget = require('./api/event_target'),
  2.     Event       = require('./api/event');
  3.  
  4. var API = {
  5.   CONNECTING:   0,
  6.   OPEN:         1,
  7.   CLOSING:      2,
  8.   CLOSED:       3,
  9.  
  10.   _open: function() {
  11.     if (this._parser && !this._parser.isOpen()) return;
  12.     this.readyState = API.OPEN;
  13.  
  14.     var buffer = this._sendBuffer || [],
  15.         message;
  16.  
  17.     while (message = buffer.shift())
  18.       this.send.apply(this, message);
  19.  
  20.     var event = new Event('open');
  21.     event.initEvent('open', false, false);
  22.     this.dispatchEvent(event);
  23.   },
  24.  
  25.   receive: function(data) {
  26.     if (this.readyState !== API.OPEN) return false;
  27.     var event = new Event('message');
  28.     event.initEvent('message', false, false);
  29.     event.data = data;
  30.     this.dispatchEvent(event);
  31.   },
  32.  
  33.   send: function(data, type, errorType) {
  34.     if (this.readyState === API.CONNECTING) {
  35.       if (this._sendBuffer) {
  36.         this._sendBuffer.push(arguments);
  37.         return true;
  38.       } else {
  39.         throw new Error('Cannot call send(), socket is not open yet');
  40.       }
  41.     }
  42.  
  43.     if (this.readyState === API.CLOSED)
  44.       return false;
  45.  
  46.     if (!(data instanceof Buffer)) data = String(data);
  47.  
  48.     var frame = this._parser.frame(data, type, errorType);
  49.     try {
  50.       this._stream.write(frame, 'binary');
  51.       return true;
  52.     } catch (e) {
  53.       return false;
  54.     }
  55.   },
  56.  
  57.   close: function(code, reason, ack) {
  58.     if (this.readyState === API.CLOSED) return;
  59.     if (this.readyState === API.CLOSING && ack !== false) return;
  60.  
  61.     var finalize = function() {
  62.       this.readyState = API.CLOSED;
  63.       if (this._pingLoop) clearInterval(this._pingLoop);
  64.       if (this._stream) this._stream.end();
  65.       var event = new Event('close', {code: code || 1000, reason: reason || ''});
  66.       event.initEvent('close', false, false);
  67.       this.dispatchEvent(event);
  68.     };
  69.  
  70.     if (this.readyState === API.CONNECTING)
  71.       return finalize.call(this);
  72.  
  73.     this.readyState = API.CLOSING;
  74.  
  75.     if (ack === false) {
  76.       if (this._parser.close) this._parser.close(code, reason);
  77.       finalize.call(this);
  78.     } else {
  79.       if (this._parser.close) this._parser.close(code, reason, finalize, this);
  80.       else finalize.call(this);
  81.     }
  82.   }
  83. };
  84.  
  85. for (var key in EventTarget) API[key] = EventTarget[key];
  86.  
  87. module.exports = API;

Raw Paste


Login or Register to edit or fork this paste. It's free.