github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/themes/wind/static/libs/sockjs-client-1.1.0/lib/transport/receiver/xhr.js (about)

     1  'use strict';
     2  
     3  var inherits = require('inherits')
     4    , EventEmitter = require('events').EventEmitter
     5    ;
     6  
     7  var debug = function() {};
     8  if (process.env.NODE_ENV !== 'production') {
     9    debug = require('debug')('sockjs-client:receiver:xhr');
    10  }
    11  
    12  function XhrReceiver(url, AjaxObject) {
    13    debug(url);
    14    EventEmitter.call(this);
    15    var self = this;
    16  
    17    this.bufferPosition = 0;
    18  
    19    this.xo = new AjaxObject('POST', url, null);
    20    this.xo.on('chunk', this._chunkHandler.bind(this));
    21    this.xo.once('finish', function(status, text) {
    22      debug('finish', status, text);
    23      self._chunkHandler(status, text);
    24      self.xo = null;
    25      var reason = status === 200 ? 'network' : 'permanent';
    26      debug('close', reason);
    27      self.emit('close', null, reason);
    28      self._cleanup();
    29    });
    30  }
    31  
    32  inherits(XhrReceiver, EventEmitter);
    33  
    34  XhrReceiver.prototype._chunkHandler = function(status, text) {
    35    debug('_chunkHandler', status);
    36    if (status !== 200 || !text) {
    37      return;
    38    }
    39  
    40    for (var idx = -1; ; this.bufferPosition += idx + 1) {
    41      var buf = text.slice(this.bufferPosition);
    42      idx = buf.indexOf('\n');
    43      if (idx === -1) {
    44        break;
    45      }
    46      var msg = buf.slice(0, idx);
    47      if (msg) {
    48        debug('message', msg);
    49        this.emit('message', msg);
    50      }
    51    }
    52  };
    53  
    54  XhrReceiver.prototype._cleanup = function() {
    55    debug('_cleanup');
    56    this.removeAllListeners();
    57  };
    58  
    59  XhrReceiver.prototype.abort = function() {
    60    debug('abort');
    61    if (this.xo) {
    62      this.xo.close();
    63      debug('close');
    64      this.emit('close', null, 'user');
    65      this.xo = null;
    66    }
    67    this._cleanup();
    68  };
    69  
    70  module.exports = XhrReceiver;