var Stream = require('stream');
var sockjs = require('sockjs-client');

module.exports = function (uri, cb) {
    if (/^\/\/[^\/]+\//.test(uri)) {
        uri = window.location.protocol + uri;
    }
    else if (!/^https?:\/\//.test(uri)) {
        uri = window.location.protocol + '//'
            + window.location.host
            + (/^\//.test(uri) ? uri : '/' + uri)
        ;
    }
    
    var stream = new Stream;
    stream.readable = true;
    stream.writable = true;
    
    var ready = false;
    var buffer = [];
    
    var sock = sockjs(uri);
    stream.sock = sock;
    
    stream.write = function (msg) {
        if (!ready) buffer.push(msg)
        else sock.send(msg)
    };
    stream.end = function (msg) {
        if (msg !== undefined) stream.write(msg);
        if (!ready) {
            stream._ended = true;
            return;
        }
        stream.writable = false;
        sock.close();
    };

    stream.destroy = function () {
        stream._ended = true;
        stream.writable = stream.readable = false;
        buffer.length = 0
        sock.close();
    }
    
    sock.onopen = function () {
        if (typeof cb === 'function') cb();
        ready = true;
        stream.emit('connect')
        buffer.forEach(function (msg) {
            sock.send(msg);
        });
        buffer = [];
        if (stream._ended) stream.end();
    };
    sock.onmessage = function (e) {
        stream.emit('data', e.data);
    };
    sock.onclose = function () {
        stream.emit('end');
        stream.writable = false;
        stream.readable = false;
    };
    
    return stream;
};

@@ -636,16 +636,33 @@
  (!ready
+ %7C%7C buffer.length
 ) buffer
@@ -1217,39 +1217,8 @@
 ue;%0A
-        stream.emit('connect')%0A
     
@@ -1310,24 +1310,55 @@
 uffer = %5B%5D;%0A
+        stream.emit('connect')%0A
         if (

Handle buffer better