diff --git a/lib/memcache.js b/lib/memcache.js index 8b826ad..43bbbec 100644 --- a/lib/memcache.js +++ b/lib/memcache.js @@ -24,10 +24,12 @@ */ var tcp = require('net'), - util = require('util'); + util = require('util'), + EventEmitter = require('events'); var crlf = "\r\n"; var crlf_len = crlf.length; +var self; var error_replies = ['ERROR', 'NOT_FOUND', 'CLIENT_ERROR', 'SERVER_ERROR']; @@ -42,12 +44,12 @@ var Client = exports.Client = function(port, host) { this.handles = []; }; -util.inherits(Client, process.EventEmitter); +util.inherits(Client, EventEmitter); Client.prototype.connect = function () { if (!this.conn) { this.conn = new tcp.createConnection(this.port, this.host); - var self = this; + self = this; this.conn.addListener("connect", function () { this.setTimeout(0); // try to stay connected. this.setNoDelay(); @@ -107,7 +109,12 @@ Client.prototype.dispatchHandles = function() { Client.prototype.query = function(query, type, callback) { this.callbacks.push({ type: type, fun: callback }); this.sends++; - this.conn.write(query + crlf); + if (this.conn !== null) { + this.conn.write(query + crlf); + } else { + // Server has crashed or in another way become unavailable, connection closed. + self.emit("close"); + } }; Client.prototype.close = function() { @@ -271,11 +278,11 @@ Client.prototype.handle_get = function(buffer) { var end_indicator_len = 3; var result_len = 0; - if (buffer.indexOf('END') == 0) { + if (buffer.lastIndexOf('END') == 0) { return [result_value, end_indicator_len + crlf_len]; - } else if (buffer.indexOf('VALUE') == 0 && buffer.indexOf('END') != -1) { + } else if (buffer.indexOf('VALUE') == 0 && buffer.lastIndexOf('END') != -1) { first_line_len = buffer.indexOf(crlf) + crlf_len; - var end_indicator_start = buffer.indexOf('END'); + var end_indicator_start = buffer.lastIndexOf('END'); result_len = end_indicator_start - first_line_len - crlf_len; result_value = buffer.substr(first_line_len, result_len); return [result_value, first_line_len + parseInt(result_len, 10) + crlf_len + end_indicator_len + crlf_len]