/**
 * Emulates stream.setTimeout() behaviour, but respects outgoing data
 * too.
 *
 * @param {Number} timeout Milliseconds
 */
exports.attach = function(stream, timeout) {
    var timer;
    var emitTimeout = function() {
        timer = undefined;
        stream.emit('timeout');
    };
    var updateTimer = function() {
        if (timer)
            clearTimeout(timer);
        timer = setTimeout(emitTimeout, timeout);
    };

    var oldWrite = stream.write;
    stream.write = function() {
        updateTimer();
        oldWrite.apply(this, arguments);
    };
    stream.addListener('data', updateTimer);
    stream.addListener('close', function() {
		if (timer)
		    clearTimeout(timer);
	    stream.write = oldWrite;
    });
    stream.addListener('end', function() {
    	if (timer)
    	    clearTimeout(timer);
        stream.write = oldWrite;
    });
};

/**
 * Emulates stream.setTimeout() behaviour, but respects outgoing data
 * too.
 *
 * @param {Number} timeout Milliseconds
 */
exports.attach = function(stream, timeout) {
    var timer;
    var emitTimeout = function() {
        timer = undefined;
        stream.emit('timeout');
    };
    var updateTimer = function() {
        if (timer)
            clearTimeout(timer);
        timer = setTimeout(emitTimeout, timeout);
    };

    var oldWrite = stream.write;
    stream.write = function() {
        updateTimer();
        oldWrite.apply(this, arguments);
    };
    stream.addListener('data', updateTimer);
    stream.addListener('close', function() {
	if (timer)
	    clearTimeout(timer);
    });
};

--- 
+++ 
@@ -23,7 +23,13 @@
     };
     stream.addListener('data', updateTimer);
     stream.addListener('close', function() {
-	if (timer)
-	    clearTimeout(timer);
+		if (timer)
+		    clearTimeout(timer);
+	    stream.write = oldWrite;
+    });
+    stream.addListener('end', function() {
+    	if (timer)
+    	    clearTimeout(timer);
+        stream.write = oldWrite;
     });
 };
Fix the memory leak issue on idle timeout
