Skip to content
This repository
Browse code

file upload example

  • Loading branch information...
commit 8411bcf9937d8ae96800a4604acd3407c9809e6c 1 parent 65d7e04
Eric Zhang authored July 25, 2012
2  examples/fileupload/README.md
Source Rendered
... ...
@@ -1,4 +1,4 @@
1  
-## Drag and Drop File Upload Example w/ Percent complete 
  1
+## Drag and Drop File Upload Example w/ Percentage completion
2 2
 
3 3
 
4 4
 1. Run the server:
933  examples/fileupload/public/binary.js
... ...
@@ -1,933 +0,0 @@
1  
-/*! binary.js build:0.0.3, development. Copyright(c) 2012 Eric Zhang <eric@ericzhang.com> MIT Licensed */
2  
-(function(exports){
3  
-/**
4  
- * Light EventEmitter. Ported from Node.js/events.js
5  
- * Eric Zhang
6  
- */
7  
-
8  
-/**
9  
- * EventEmitter class
10  
- * Creates an object with event registering and firing methods
11  
- */
12  
-function EventEmitter() {
13  
-  // Initialise required storage variables
14  
-  this._events = {};
15  
-}
16  
-
17  
-var isArray = Array.isArray;
18  
-
19  
-
20  
-EventEmitter.prototype.addListener = function(type, listener, scope, once) {
21  
-  if ('function' !== typeof listener) {
22  
-    throw new Error('addListener only takes instances of Function');
23  
-  }
24  
-  
25  
-  // To avoid recursion in the case that type == "newListeners"! Before
26  
-  // adding it to the listeners, first emit "newListeners".
27  
-  this.emit('newListener', type, typeof listener.listener === 'function' ?
28  
-            listener.listener : listener);
29  
-            
30  
-  if (!this._events[type]) {
31  
-    // Optimize the case of one listener. Don't need the extra array object.
32  
-    this._events[type] = listener;
33  
-  } else if (isArray(this._events[type])) {
34  
-
35  
-    // If we've already got an array, just append.
36  
-    this._events[type].push(listener);
37  
-
38  
-  } else {
39  
-    // Adding the second element, need to change to array.
40  
-    this._events[type] = [this._events[type], listener];
41  
-  }
42  
-  
43  
-};
44  
-
45  
-EventEmitter.prototype.on = EventEmitter.prototype.addListener;
46  
-
47  
-EventEmitter.prototype.once = function(type, listener, scope) {
48  
-  if ('function' !== typeof listener) {
49  
-    throw new Error('.once only takes instances of Function');
50  
-  }
51  
-
52  
-  var self = this;
53  
-  function g() {
54  
-    self.removeListener(type, g);
55  
-    listener.apply(this, arguments);
56  
-  };
57  
-
58  
-  g.listener = listener;
59  
-  self.on(type, g);
60  
-
61  
-  return this;
62  
-};
63  
-
64  
-EventEmitter.prototype.removeListener = function(type, listener, scope) {
65  
-  if ('function' !== typeof listener) {
66  
-    throw new Error('removeListener only takes instances of Function');
67  
-  }
68  
-
69  
-  // does not use listeners(), so no side effect of creating _events[type]
70  
-  if (!this._events[type]) return this;
71  
-
72  
-  var list = this._events[type];
73  
-
74  
-  if (isArray(list)) {
75  
-    var position = -1;
76  
-    for (var i = 0, length = list.length; i < length; i++) {
77  
-      if (list[i] === listener ||
78  
-          (list[i].listener && list[i].listener === listener))
79  
-      {
80  
-        position = i;
81  
-        break;
82  
-      }
83  
-    }
84  
-
85  
-    if (position < 0) return this;
86  
-    list.splice(position, 1);
87  
-    if (list.length == 0)
88  
-      delete this._events[type];
89  
-  } else if (list === listener ||
90  
-             (list.listener && list.listener === listener))
91  
-  {
92  
-    delete this._events[type];
93  
-  }
94  
-
95  
-  return this;
96  
-};
97  
-
98  
-
99  
-EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
100  
-
101  
-
102  
-EventEmitter.prototype.removeAllListeners = function(type) {
103  
-  if (arguments.length === 0) {
104  
-    this._events = {};
105  
-    return this;
106  
-  }
107  
-
108  
-  // does not use listeners(), so no side effect of creating _events[type]
109  
-  if (type && this._events && this._events[type]) this._events[type] = null;
110  
-  return this;
111  
-};
112  
-
113  
-EventEmitter.prototype.listeners = function(type) {
114  
-  if (!this._events[type]) this._events[type] = [];
115  
-  if (!isArray(this._events[type])) {
116  
-    this._events[type] = [this._events[type]];
117  
-  }
118  
-  return this._events[type];
119  
-};
120  
-
121  
-EventEmitter.prototype.emit = function(type) {
122  
-  var type = arguments[0];
123  
-  var handler = this._events[type];
124  
-  if (!handler) return false;
125  
-
126  
-  if (typeof handler == 'function') {
127  
-    switch (arguments.length) {
128  
-      // fast cases
129  
-      case 1:
130  
-        handler.call(this);
131  
-        break;
132  
-      case 2:
133  
-        handler.call(this, arguments[1]);
134  
-        break;
135  
-      case 3:
136  
-        handler.call(this, arguments[1], arguments[2]);
137  
-        break;
138  
-      // slower
139  
-      default:
140  
-        var l = arguments.length;
141  
-        var args = new Array(l - 1);
142  
-        for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
143  
-        handler.apply(this, args);
144  
-    }
145  
-    return true;
146  
-
147  
-  } else if (isArray(handler)) {
148  
-    var l = arguments.length;
149  
-    var args = new Array(l - 1);
150  
-    for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
151  
-
152  
-    var listeners = handler.slice();
153  
-    for (var i = 0, l = listeners.length; i < l; i++) {
154  
-      listeners[i].apply(this, args);
155  
-    }
156  
-    return true;
157  
-  } else {
158  
-    return false;
159  
-  }
160  
-};
161  
-
162  
-
163  
-
164  
-
165  
-var util = {
166  
-  inherits: function(ctor, superCtor) {
167  
-    ctor.super_ = superCtor;
168  
-    ctor.prototype = Object.create(superCtor.prototype, {
169  
-      constructor: {
170  
-        value: ctor,
171  
-        enumerable: false,
172  
-        writable: true,
173  
-        configurable: true
174  
-      }
175  
-    });
176  
-  },
177  
-  extend: function(dest, source) {
178  
-    for(var key in source) {
179  
-      if(source.hasOwnProperty(key)) {
180  
-        dest[key] = source[key];
181  
-      }
182  
-    }
183  
-    return dest;
184  
-  },
185  
-  info: console.log.bind(console),
186  
-  pack: BinaryPack.pack,
187  
-  unpack: BinaryPack.unpack,
188  
-  setZeroTimeout: (function(global) {
189  
-    var timeouts = [];
190  
-    var messageName = 'zero-timeout-message';
191  
-
192  
-    // Like setTimeout, but only takes a function argument.	 There's
193  
-    // no time argument (always zero) and no arguments (you have to
194  
-    // use a closure).
195  
-    function setZeroTimeoutPostMessage(fn) {
196  
-      timeouts.push(fn);
197  
-      global.postMessage(messageName, '*');
198  
-    }		
199  
-
200  
-    function handleMessage(event) {
201  
-      if (event.source == global && event.data == messageName) {
202  
-        if (event.stopPropagation) {
203  
-          event.stopPropagation();
204  
-        }
205  
-        if (timeouts.length) {
206  
-          timeouts.shift()();
207  
-        }
208  
-      }
209  
-    }
210  
-    if (global.addEventListener) {
211  
-      global.addEventListener('message', handleMessage, true);
212  
-    } else if (global.attachEvent) {
213  
-      global.attachEvent('onmessage', handleMessage);
214  
-    }
215  
-    return setZeroTimeoutPostMessage;
216  
-  }(this))
217  
-};
218  
-
219  
-
220  
-
221  
-function Stream() {
222  
-  EventEmitter.call(this);
223  
-}
224  
-
225  
-util.inherits(Stream, EventEmitter);
226  
-
227  
-Stream.prototype.pipe = function(dest, options) {
228  
-  var source = this;
229  
-
230  
-  function ondata(chunk) {
231  
-    if (dest.writable) {
232  
-      if (false === dest.write(chunk) && source.pause) {
233  
-        source.pause();
234  
-      }
235  
-    }
236  
-  }
237  
-
238  
-  source.on('data', ondata);
239  
-
240  
-  function ondrain() {
241  
-    if (source.readable && source.resume) {
242  
-      source.resume();
243  
-    }
244  
-  }
245  
-
246  
-  dest.on('drain', ondrain);
247  
-
248  
-  // If the 'end' option is not supplied, dest.end() will be called when
249  
-  // source gets the 'end' or 'close' events.  Only dest.end() once.
250  
-  if (!dest._isStdio && (!options || options.end !== false)) {
251  
-    source.on('end', onend);
252  
-    source.on('close', onclose);
253  
-  }
254  
-
255  
-  var didOnEnd = false;
256  
-  function onend() {
257  
-    if (didOnEnd) return;
258  
-    didOnEnd = true;
259  
-
260  
-    dest.end();
261  
-  }
262  
-
263  
-
264  
-  function onclose() {
265  
-    if (didOnEnd) return;
266  
-    didOnEnd = true;
267  
-
268  
-    dest.destroy();
269  
-  }
270  
-
271  
-  // don't leave dangling pipes when there are errors.
272  
-  function onerror(er) {
273  
-    cleanup();
274  
-    if (this.listeners('error').length === 0) {
275  
-      throw er; // Unhandled stream error in pipe.
276  
-    }
277  
-  }
278  
-
279  
-  source.on('error', onerror);
280  
-  dest.on('error', onerror);
281  
-
282  
-  // remove all the event listeners that were added.
283  
-  function cleanup() {
284  
-    source.removeListener('data', ondata);
285  
-    dest.removeListener('drain', ondrain);
286  
-
287  
-    source.removeListener('end', onend);
288  
-    source.removeListener('close', onclose);
289  
-
290  
-    source.removeListener('error', onerror);
291  
-    dest.removeListener('error', onerror);
292  
-
293  
-    source.removeListener('end', cleanup);
294  
-    source.removeListener('close', cleanup);
295  
-
296  
-    dest.removeListener('end', cleanup);
297  
-    dest.removeListener('close', cleanup);
298  
-  }
299  
-
300  
-  source.on('end', cleanup);
301  
-  source.on('close', cleanup);
302  
-
303  
-  dest.on('end', cleanup);
304  
-  dest.on('close', cleanup);
305  
-
306  
-  dest.emit('pipe', source);
307  
-
308  
-  // Allow for unix-like usage: A.pipe(B).pipe(C)
309  
-  return dest;
310  
-};
311  
-function BlobReadStream(source, options){
312  
-  Stream.call(this);
313  
-  
314  
-  options = util.extend({
315  
-      readDelay: 0,
316  
-      paused: false
317  
-  }, options);
318  
-  
319  
-  this._source = source;
320  
-  this._start = 0;
321  
-  this._readChunkSize = options.chunkSize || source.size;
322  
-  this._readDelay = options.readDelay;
323  
-  
324  
-  this.readable = true;
325  
-  this.paused = options.paused;
326  
-  
327  
-  this._read();
328  
-}
329  
-
330  
-util.inherits(BlobReadStream, Stream);
331  
-
332  
-
333  
-BlobReadStream.prototype.pause = function(){
334  
-  this.paused = true;
335  
-};
336  
-
337  
-BlobReadStream.prototype.resume = function(){
338  
-  this.paused = false;
339  
-  this._read();
340  
-};
341  
-
342  
-BlobReadStream.prototype.destroy = function(){
343  
-  this.readable = false;
344  
-  clearTimeout(this._timeoutId);
345  
-};
346  
-
347  
-BlobReadStream.prototype._read = function(){
348  
-    
349  
-  var self = this;
350  
-  
351  
-  function emitReadChunk(){
352  
-    self._emitReadChunk();
353  
-  }
354  
-  
355  
-  var readDelay = this._readDelay;
356  
-  if (readDelay !== 0){
357  
-    this._timeoutId = setTimeout(emitReadChunk, readDelay);
358  
-  } else {
359  
-    util.setZeroTimeout(emitReadChunk);
360  
-  }
361  
-    
362  
-};
363  
-
364  
-BlobReadStream.prototype._emitReadChunk = function(){
365  
-    
366  
-  if(this.paused || !this.readable) return;
367  
-  
368  
-  var chunkSize = Math.min(this._source.size - this._start, this._readChunkSize);
369  
-  
370  
-  if(chunkSize === 0){
371  
-      this.readable = false;
372  
-      this.emit("end");
373  
-      return;
374  
-  }
375  
-  
376  
-  var sourceEnd = this._start + chunkSize;
377  
-  var chunk = (this._source.slice || this._source.webkitSlice || this._source.mozSlice).call(this._source, this._start, sourceEnd);
378  
-  
379  
-  this._start = sourceEnd;
380  
-  this._read();
381  
-  
382  
-  this.emit("data", chunk);
383  
-  
384  
-};
385  
-
386  
-/*
387  
-
388  
-
389  
-
390  
-
391  
-function BlobWriteStream(options){
392  
-    
393  
-    stream.Stream.call(this);
394  
-    
395  
-    options = _.extend({
396  
-        onFull: onFull,
397  
-        onEnd: function(){},
398  
-        minBlockAllocSize: 0,
399  
-        drainDelay:0
400  
-    }, options);
401  
-    
402  
-    this._onFull = options.onFull;
403  
-    this._onEnd = options.onEnd;
404  
-    this._onWrite = options.onWrite;
405  
-    
406  
-    this._minBlockAllocSize = options.minBlockAllocSize;
407  
-    this._maxBlockAllocSize = options.maxBlockAllocSize;
408  
-    this._drainDelay = options.drainDelay;
409  
-    
410  
-    this._buffer = new Buffer(options.minBlockAllocSize);
411  
-    this._destination = this._buffer;
412  
-    this._destinationPos = 0;
413  
-    
414  
-    this._writeQueue = [];
415  
-    this._pendingOnFull = false;
416  
-    this._pendingQueueDrain = false;
417  
-    
418  
-    this.writable = true;
419  
-    this.bytesWritten = 0;
420  
-}
421  
-
422  
-util.inherits(BlobWriteStream, stream.Stream);
423  
-
424  
-BlobWriteStream.prototype.getBuffer = function(){
425  
-    return this._buffer;
426  
-};
427  
-
428  
-BlobWriteStream.prototype.write = function(data, encoding){
429  
-    
430  
-    if(!this.writable){
431  
-        throw new Error("stream is not writable");
432  
-    }
433  
-    
434  
-    if(!Buffer.isBuffer(data)){
435  
-        data = new Buffer(data, encoding);
436  
-    }
437  
-    
438  
-    if(data.length){
439  
-        this._writeQueue.push(data);
440  
-    }
441  
-    
442  
-    this._commit();
443  
-    
444  
-    return this._writeQueue.length === 0;
445  
-};
446  
-
447  
-BlobWriteStream.prototype._commit = function(){
448  
-    
449  
-    var self = this;
450  
-    
451  
-    var destination = this._destination;
452  
-    var writeQueue = this._writeQueue;
453  
-    
454  
-    var startDestinationPos = this._destinationPos;
455  
-    
456  
-    while(writeQueue.length && destination.length){
457  
-        
458  
-        var head = writeQueue[0];
459  
-        
460  
-        var copySize = Math.min(destination.length, head.length);
461  
-        
462  
-        head.copy(destination, 0, 0, copySize);
463  
-        
464  
-        head = head.slice(copySize);
465  
-        destination = destination.slice(copySize);
466  
-        
467  
-        this.bytesWritten += copySize;
468  
-        this._destinationPos += copySize;
469  
-        
470  
-        if(head.length === 0){
471  
-            writeQueue.shift();
472  
-        }
473  
-        else{
474  
-            writeQueue[0] = head;
475  
-        }
476  
-    }
477  
-    
478  
-    this._destination = destination;
479  
-    
480  
-    bytesCommitted = this._destinationPos - startDestinationPos;
481  
-    if(bytesCommitted){
482  
-        if(this._onWrite){
483  
-            
484  
-            if(writeQueue.length){
485  
-                this._pendingQueueDrain = true;
486  
-            }
487  
-            
488  
-            // By locking destination the buffer is frozen and the onWrite
489  
-            // callback cannot miss any write commits
490  
-            this._destination = emptyBuffer;
491  
-            
492  
-            var consumer = this._onWrite;
493  
-            this._onWrite = null;
494  
-            
495  
-            consumer.call(this, function(nextCallback){
496  
-                util.setZeroTimeout(function(){
497  
-                    self._destination = destination;
498  
-                    self._onWrite = nextCallback;
499  
-                    self._commit();
500  
-                });
501  
-            }, consumer);
502  
-            
503  
-            return;
504  
-        }
505  
-    }
506  
-    
507  
-    if(writeQueue.length){
508  
-        
509  
-        this._pendingQueueDrain = true;
510  
-        this._growBuffer();
511  
-    }
512  
-    else if(this._pendingQueueDrain){
513  
-        
514  
-        this._pendingQueueDrain = false;
515  
-        
516  
-        if(this._drainDelay !== 0){
517  
-            setTimeout(function(){
518  
-                self.emit("drain");
519  
-            }, this._drainDelay);
520  
-        }
521  
-        else{
522  
-            util.setZeroTimeout(function(){
523  
-                self.emit("drain");
524  
-            });
525  
-        }
526  
-    }
527  
-};
528  
-
529  
-BlobWriteStream.prototype._growBuffer = function(){
530  
-    
531  
-    var self = this;
532  
-    var writeQueue = this._writeQueue;
533  
-    
534  
-    var requestSize = this._minBlockAllocSize;
535  
-    
536  
-    var maxBlockAllocSize = this._maxBlockAllocSize;
537  
-    var add = (maxBlockAllocSize === undefined ? function(a, b){return a + b;} : function(a, b){return Math.min(a + b, maxBlockAllocSize);});
538  
-    
539  
-    for(var i = 0, queueLength = writeQueue.length; i < queueLength; i++){
540  
-        requestSize = add(requestSize, writeQueue[i].length);
541  
-    }
542  
-    
543  
-    // Prevent concurrent onFull callbacks
544  
-    if(this._pendingOnFull){
545  
-        return;
546  
-    }
547  
-    this._pendingOnFull = true;
548  
-    
549  
-    this._onFull(this._buffer, requestSize, function(buffer, destination){
550  
-        util.setZeroTimeout(function(){
551  
-            
552  
-            self._pendingOnFull = false;
553  
-            
554  
-            if(!destination){
555  
-                if(self.writable){
556  
-                    self.emit("error", new Error("buffer is full"));
557  
-                }
558  
-                self.destroy();
559  
-                return;
560  
-            }
561  
-            
562  
-            self._buffer = buffer;
563  
-            self._destination = destination;
564  
-            
565  
-            self._commit();
566  
-        });
567  
-    });
568  
-};
569  
-
570  
-BlobWriteStream.prototype.end = function(data, encoding){
571  
-    
572  
-    var self = this;
573  
-    
574  
-    function _end(){
575  
-        self.writable = false;
576  
-        self._onEnd();
577  
-    }
578  
-    
579  
-    if(data){
580  
-        if(this.write(data, encoding)){
581  
-            _end();
582  
-        }else{
583  
-            self.writable = false;
584  
-            this.once("drain", _end);
585  
-        }
586  
-    }
587  
-    else{
588  
-        _end();
589  
-    }
590  
-};
591  
-
592  
-BlobWriteStream.prototype.destroy = function(){
593  
-    this.writable = false;
594  
-    this._pendingQueueDrain = false;
595  
-    this._writeQueue = [];
596  
-};
597  
-
598  
-BlobWriteStream.prototype.consume = function(consume){
599  
-    
600  
-    this._buffer = this._buffer.slice(consume);
601  
-    this._destinationPos -= consume;
602  
-};
603  
-
604  
-BlobWriteStream.prototype.getCommittedSlice = function(){
605  
-    return this._buffer.slice(0, this._destinationPos);
606  
-};
607  
-
608  
-function onFull(buffer, extraSize, callback){
609  
-    var newBuffer = new Buffer(buffer.length + extraSize);
610  
-    buffer.copy(newBuffer);
611  
-    callback(newBuffer, newBuffer.slice(buffer.length));
612  
-}
613  
-*/
614  
-exports.BlobReadStream = BlobReadStream;
615  
-
616  
-function BinaryStream(socket, id, create, meta) {
617  
-  if (!(this instanceof BinaryStream)) return new BinaryStream(options);
618  
-  
619  
-  var self = this;
620  
-  
621  
-  Stream.call(this);
622  
-
623  
-  
624  
-  this.id = id;
625  
-  this._socket = socket;
626  
-  this._socket.addEventListener('error', function(error){
627  
-    self.readable = false;
628  
-    self.writable = false;
629  
-    self.emit('error', error);
630  
-  });
631  
-  this._socket.addEventListener('close', function(code, message){
632  
-    self.readable = false;
633  
-    self.writable = false;
634  
-    self.emit('close', code, message);
635  
-  });
636  
-  
637  
-  
638  
-  this.writable = true;
639  
-  this.readable = true;
640  
-  this.paused = false;
641  
-  
642  
-  this._ended = false;
643  
-  
644  
-  if(create) {
645  
-    // This is a stream we are creating
646  
-    this._write(1, meta, this.id);
647  
-  }
648  
-}
649  
-
650  
-util.inherits(BinaryStream, Stream);
651  
-
652  
-
653  
-BinaryStream.prototype._onClose = function() {
654  
-  // Emit close event
655  
-  this.readable = false;
656  
-  this.writable = false;
657  
-  this.emit('close');
658  
-};
659  
-
660  
-// Write stream
661  
-
662  
-BinaryStream.prototype._onPause = function() {
663  
-  // Emit pause event
664  
-  this.emit('pause');
665  
-  this.paused = true;
666  
-};
667  
-
668  
-BinaryStream.prototype._onResume = function() {
669  
-  // Emit resume event
670  
-  this.emit('resume');
671  
-  this.emit('drain');
672  
-  this.paused = false;
673  
-};
674  
-
675  
-BinaryStream.prototype._write = function(code, data, bonus, cb) {
676  
-  var message = util.pack([code, data, bonus]);
677  
-  return this._socket.send(message, {binary: true}, cb) !== false;
678  
-};
679  
-
680  
-BinaryStream.prototype.write = function(data, cb) {
681  
-  if(this.writable) {
682  
-    var out = this._write(2, data, this.id, cb);
683  
-    return !this.paused && out;
684  
-  } else {
685  
-    throw new Error('Stream is not writable');
686  
-  }
687  
-};
688  
-
689  
-BinaryStream.prototype.end = function() {
690  
-  this._onEnd();
691  
-  this._write(5, null, this.id);
692  
-};
693  
-
694  
-BinaryStream.prototype.destroy = BinaryStream.prototype.destroySoon = function() {
695  
-  this._onClose();
696  
-  this._write(6, null, this.id);
697  
-};
698  
-
699  
-
700  
-// Read stream
701  
-
702  
-BinaryStream.prototype._onEnd = function() {
703  
-  if(this._ended) return;
704  
-  
705  
-  this._ended = true;
706  
-  this.readable = false;
707  
-  this.emit('end');
708  
-};
709  
-
710  
-BinaryStream.prototype._onData = function(data) {
711  
-  // Dispatch 
712  
-  this.emit('data', data);
713  
-};
714  
-
715  
-BinaryStream.prototype.pause = function() {
716  
-  this._onPause();
717  
-  this._write(3, null, this.id);
718  
-};
719  
-
720  
-BinaryStream.prototype.resume = function() {
721  
-  this._onResume();
722  
-  this._write(4, null, this.id);
723  
-};
724  
-
725  
-
726  
-function BinaryClient(socket, options) {
727  
-  if (!(this instanceof BinaryClient)) return new BinaryClient(options);
728  
-  
729  
-  EventEmitter.call(this);
730  
-  
731  
-  var self = this;
732  
-  
733  
-  this._options = util.extend({
734  
-    chunkSize: 40960
735  
-  }, options);
736  
-  
737  
-  this._streams = {};
738  
-  
739  
-  // Use even numbered ids for client orignated streams
740  
-  this._nextId = 0;
741  
-  
742  
-  
743  
-  if(typeof socket === 'string') {
744  
-    this._socket = new WebSocket(socket);
745  
-  } else {
746  
-    this._socket = socket;
747  
-  }
748  
-  
749  
-  this._socket.binaryType = 'arraybuffer';
750  
-  
751  
-  this._socket.addEventListener('open', function(){
752  
-    self.emit('open');
753  
-  });
754  
-  this._socket.addEventListener('error', function(error){
755  
-    self.emit('error', error);
756  
-  });
757  
-  this._socket.addEventListener('close', function(code, message){
758  
-    self.emit('close', code, message);
759  
-  });
760  
-  this._socket.addEventListener('message', function(data, flags){
761  
-    util.setZeroTimeout(function(){
762  
-  
763  
-      // Message format
764  
-      // [type, payload, bonus ]
765  
-      //
766  
-      // Reserved
767  
-      // [ 0  , X , X ]
768  
-      // 
769  
-      //
770  
-      // New stream
771  
-      // [ 1  , Meta , new streamId ]
772  
-      // 
773  
-      //
774  
-      // Data
775  
-      // [ 2  , Data , streamId ]
776  
-      // 
777  
-      //
778  
-      // Pause
779  
-      // [ 3  , null , streamId ]
780  
-      // 
781  
-      //
782  
-      // Resume
783  
-      // [ 4  , null , streamId ]
784  
-      // 
785  
-      //
786  
-      // End
787  
-      // [ 5  , null , streamId ]
788  
-      // 
789  
-      //
790  
-      // Close
791  
-      // [ 6  , null , streamId ]
792  
-      // 
793  
-      
794  
-      if(data.hasOwnProperty('data')){
795  
-        data = data.data;
796  
-      }
797  
-      
798  
-      data = util.unpack(data);
799  
-      switch(data[0]) {
800  
-        case 0:
801  
-          // Reserved
802  
-          break;
803  
-        case 1:
804  
-          var meta = data[1];
805  
-          var streamId = data[2];
806  
-          var binaryStream = self._receiveStream(streamId);
807  
-          self.emit('stream', binaryStream, meta);
808  
-          break;
809  
-        case 2:
810  
-          var payload = data[1];
811  
-          var streamId = data[2];
812  
-          var binaryStream = self._streams[streamId];
813  
-          if(binaryStream) {
814  
-            binaryStream._onData(payload);
815  
-          } else {
816  
-            self.emit('error', 'Received `data` message for unknown stream: ' + streamId);
817  
-          }
818  
-          break;
819  
-        case 3:
820  
-          var streamId = data[2];
821  
-          var binaryStream = self._streams[streamId];
822  
-          if(binaryStream) {
823  
-            binaryStream._onPause();
824  
-          } else {
825  
-            self.emit('error', 'Received `pause` message for unknown stream: ' + streamId);
826  
-          }
827  
-          break;
828  
-        case 4:
829  
-          var streamId = data[2];
830  
-          var binaryStream = self._streams[streamId];
831  
-          if(binaryStream) {
832  
-            binaryStream._onResume();
833  
-          } else {
834  
-            self.emit('error', 'Received `resume` message for unknown stream: ' + streamId);
835  
-          }
836  
-          break;
837  
-        case 5:
838  
-          var streamId = data[2];
839  
-          var binaryStream = self._streams[streamId];
840  
-          if(binaryStream) {
841  
-            binaryStream._onEnd();
842  
-          } else {
843  
-            self.emit('error', 'Received `end` message for unknown stream: ' + streamId);
844  
-          }
845  
-          break;
846  
-        case 6:
847  
-          var streamId = data[2];
848  
-          var binaryStream = self._streams[streamId];
849  
-          if(binaryStream) {
850  
-            binaryStream._onClose();
851  
-            delete self._streams[streamId];
852  
-          } else {
853  
-            self.emit('error', 'Received `close` message for unknown stream: ' + streamId);
854  
-          }
855  
-          break;
856  
-        default:
857  
-          self.emit('error', 'Unrecognized message type received: ' + data[0]);
858  
-      }
859  
-    });
860  
-  });
861  
-}
862  
-
863  
-util.inherits(BinaryClient, EventEmitter);
864  
-
865  
-BinaryClient.prototype.send = function(data, meta){
866  
-  var stream = this.createStream(meta);
867  
-  if(data instanceof Stream) {
868  
-    data.pipe(stream);
869  
-  } else if (util.isNode === true) {
870  
-    if(Buffer.isBuffer(data)) {
871  
-      (new BufferReadStream(data, {chunkSize: this._options.chunkSize})).pipe(stream);
872  
-    } else {
873  
-      stream.write(data);
874  
-    } 
875  
-  } else if (util.isNode !== true) {
876  
-    if(data.constructor == Blob || data.constructor == File) {
877  
-      (new BlobReadStream(data, {chunkSize: this._options.chunkSize})).pipe(stream);
878  
-    } else if (data.constructor == ArrayBuffer) {
879  
-      var blob;
880  
-      if(binaryFeatures.useArrayBufferView) {
881  
-        data = new Uint8Array(data.buffer);
882  
-      }
883  
-      if(binaryFeatures.useBlobBuilder) {
884  
-        var builder = new BlobBuilder();
885  
-        builder.append(data);
886  
-        blob = builder.getBlob()
887  
-      } else {
888  
-        blob = new Blob([data]);
889  
-      }
890  
-      (new BlobReadStream(blob, {chunkSize: this._options.chunkSize})).pipe(stream);
891  
-    } else if (typeof data === 'object' && 'BYTES_PER_ELEMENT' in data) {
892  
-      var blob;
893  
-      if(!binaryFeatures.useArrayBufferView) {
894  
-        // Warn
895  
-        data = data.buffer;
896  
-      }
897  
-      if(binaryFeatures.useBlobBuilder) {
898  
-        var builder = new BlobBuilder();
899  
-        builder.append(data);
900  
-        blob = builder.getBlob()
901  
-      } else {
902  
-        blob = new Blob([data]);
903  
-      }
904  
-      (new BlobReadStream(blob, {chunkSize: this._options.chunkSize})).pipe(stream);
905  
-    } else {
906  
-      stream.write(data);
907  
-    }
908  
-  }
909  
-  return stream;
910  
-};
911  
-
912  
-BinaryClient.prototype._receiveStream = function(streamId){
913  
-  var binaryStream = new BinaryStream(this._socket, streamId, false);
914  
-  this._streams[streamId] = binaryStream;
915  
-  return binaryStream;
916  
-};
917  
-
918  
-BinaryClient.prototype.createStream = function(meta){
919  
-  var streamId = this._nextId;
920  
-  this._nextId += 2;
921  
-  var binaryStream = new BinaryStream(this._socket, streamId, true, meta);
922  
-  this._streams[streamId] = binaryStream;
923  
-  return binaryStream;
924  
-};
925  
-
926  
-BinaryClient.prototype.close = BinaryClient.prototype.destroy = function(code, message) {
927  
-  this._socket.close(code, message);
928  
-};
929  
-
930  
-
931  
-exports.BinaryClient = BinaryClient;
932  
-
933  
-})(this);
567  examples/fileupload/public/binarypack.js
... ...
@@ -1,567 +0,0 @@
1  
-/*! binarypack.js build:0.0.2, development. Copyright(c) 2012 Eric Zhang <eric@ericzhang.com> MIT Licensed */
2  
-(function(exports){
3  
-exports.binaryFeatures = {
4  
-  useBlobBuilder: (function(){
5  
-    try {
6  
-      new Blob([]);
7  
-      return false;
8  
-    } catch (e) {
9  
-      return true;
10  
-    }
11  
-  })(),
12  
-  useArrayBufferView: (function(){
13  
-    try {
14  
-      return (new Blob([new Uint8Array([])])).size === 0;
15  
-    } catch (e) {
16  
-      return true;
17  
-    }
18  
-  })(),
19  
-  supportsBinaryWebsockets: (function(){
20  
-    try {
21  
-      var wstest = new WebSocket('ws://localhost:0');
22  
-      if (typeof(wstest.binaryType) !== "undefined") {
23  
-        return true;
24  
-      } else {
25  
-        return false;
26  
-      }
27  
-      wstest.close();
28  
-      wstest = null;
29  
-    } catch (e) {
30  
-      return false;
31  
-    }
32  
-  })()
33  
-};
34  
-
35  
-exports.BlobBuilder = window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder || window.BlobBuilder;
36  
-
37  
-function BufferBuilder(){
38  
-  this._pieces = [];
39  
-  this._parts = [];
40  
-}
41  
-
42  
-BufferBuilder.prototype.append = function(data) {
43  
-  if(typeof data === 'number') {
44  
-    this._pieces.push(data);
45  
-  } else {
46  
-    this._flush();
47  
-    this._parts.push(data);
48  
-  }
49  
-};
50  
-
51  
-BufferBuilder.prototype._flush = function() {
52  
-  if (this._pieces.length > 0) {    
53  
-    var buf = new Uint8Array(this._pieces);
54  
-    if(!binaryFeatures.useArrayBufferView) {
55  
-      buf = buf.buffer;
56  
-    }
57  
-    this._parts.push(buf);
58  
-    this._pieces = [];
59  
-  }
60  
-};
61  
-
62  
-BufferBuilder.prototype.getBuffer = function() {
63  
-  this._flush();
64  
-  if(binaryFeatures.useBlobBuilder) {
65  
-    var builder = new BlobBuilder();
66  
-    for(var i = 0, ii = this._parts.length; i < ii; i++) {
67  
-      builder.append(this._parts[i]);
68  
-    }
69  
-    return builder.getBlob();
70  
-  } else {
71  
-    return new Blob(this._parts);
72  
-  }
73  
-};
74  
-exports.BinaryPack = {
75  
-  unpack: function(data){
76  
-    var unpacker = new Unpacker(data);
77  
-    return unpacker.unpack();
78  
-  },
79  
-  pack: function(data){
80  
-    var packer = new Packer();
81  
-    var buffer = packer.pack(data);
82  
-    return buffer;
83  
-  }
84  
-};
85  
-
86  
-function Unpacker (data){
87  
-  // Data is ArrayBuffer
88  
-  this.index = 0;
89  
-  this.dataBuffer = data;
90  
-  this.dataView = new Uint8Array(this.dataBuffer);
91  
-  this.length = this.dataBuffer.byteLength;
92  
-}
93  
-
94  
-
95  
-Unpacker.prototype.unpack = function(){
96  
-  var type = this.unpack_uint8();
97  
-  if (type < 0x80){
98  
-    var positive_fixnum = type;
99  
-    return positive_fixnum;
100  
-  } else if ((type ^ 0xe0) < 0x20){
101  
-    var negative_fixnum = (type ^ 0xe0) - 0x20;
102  
-    return negative_fixnum;
103  
-  }
104  
-  var size;
105  
-  if ((size = type ^ 0xa0) <= 0x0f){
106  
-    return this.unpack_raw(size);
107  
-  } else if ((size = type ^ 0xb0) <= 0x0f){
108  
-    return this.unpack_string(size);
109  
-  } else if ((size = type ^ 0x90) <= 0x0f){
110  
-    return this.unpack_array(size);
111  
-  } else if ((size = type ^ 0x80) <= 0x0f){
112  
-    return this.unpack_map(size);
113  
-  }
114  
-  switch(type){
115  
-    case 0xc0:
116  
-      return null;
117  
-    case 0xc1:
118  
-      return undefined;
119  
-    case 0xc2:
120  
-      return false;
121  
-    case 0xc3:
122  
-      return true;
123  
-    case 0xca:
124  
-      return this.unpack_float();
125  
-    case 0xcb:
126  
-      return this.unpack_double();
127  
-    case 0xcc:
128  
-      return this.unpack_uint8();
129  
-    case 0xcd:
130  
-      return this.unpack_uint16();
131  
-    case 0xce:
132  
-      return this.unpack_uint32();
133  
-    case 0xcf:
134  
-      return this.unpack_uint64();
135  
-    case 0xd0:
136  
-      return this.unpack_int8();
137  
-    case 0xd1:
138  
-      return this.unpack_int16();
139  
-    case 0xd2:
140  
-      return this.unpack_int32();
141  
-    case 0xd3:
142  
-      return this.unpack_int64();
143  
-    case 0xd4:
144  
-      return undefined;
145  
-    case 0xd5:
146  
-      return undefined;
147  
-    case 0xd6:
148  
-      return undefined;
149  
-    case 0xd7:
150  
-      return undefined;
151  
-    case 0xd8:
152  
-      size = this.unpack_uint16();
153  
-      return this.unpack_string(size);
154  
-    case 0xd9:
155  
-      size = this.unpack_uint32();
156  
-      return this.unpack_string(size);
157  
-    case 0xda:
158  
-      size = this.unpack_uint16();
159  
-      return this.unpack_raw(size);
160  
-    case 0xdb:
161  
-      size = this.unpack_uint32();
162  
-      return this.unpack_raw(size);
163  
-    case 0xdc:
164  
-      size = this.unpack_uint16();
165  
-      return this.unpack_array(size);
166  
-    case 0xdd:
167  
-      size = this.unpack_uint32();
168  
-      return this.unpack_array(size);
169  
-    case 0xde:
170  
-      size = this.unpack_uint16();
171  
-      return this.unpack_map(size);
172  
-    case 0xdf:
173  
-      size = this.unpack_uint32();
174  
-      return this.unpack_map(size);
175  
-  }
176  
-}
177  
-
178  
-Unpacker.prototype.unpack_uint8 = function(){
179  
-  var byte = this.dataView[this.index] & 0xff;
180  
-  this.index++;
181  
-  return byte;
182  
-};
183  
-
184  
-Unpacker.prototype.unpack_uint16 = function(){
185  
-  var bytes = this.read(2);
186  
-  var uint16 =
187  
-    ((bytes[0] & 0xff) * 256) + (bytes[1] & 0xff);
188  
-  this.index += 2;
189  
-  return uint16;
190  
-}
191  
-
192  
-Unpacker.prototype.unpack_uint32 = function(){
193  
-  var bytes = this.read(4);
194  
-  var uint32 =
195  
-     ((bytes[0]  * 256 +
196