Skip to content

Commit a281402

Browse files
Allows a timeout on socket connection.
1 parent 1e4b28c commit a281402

File tree

1 file changed

+21
-8
lines changed

1 file changed

+21
-8
lines changed

index.js

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ function RedisClient(stream, options) {
6666
this.server_info = {};
6767
this.auth_pass = null;
6868
this.parser_module = null;
69-
this.selected_db = null; // save the selected db here, used when reconnecting
69+
this.selected_db = null; // save the selected db here, used when reconnecting
7070

7171
this.old_state = null;
7272

@@ -93,14 +93,23 @@ RedisClient.prototype.initialize_stream_listeners = function () {
9393
self.on_error(msg.message);
9494
});
9595

96-
this.stream.on("close", function () {
97-
self.connection_gone("close");
96+
this.stream.on("close", function (had_error) {
97+
if(had_error !== true){
98+
// Only in case the error event wasn't emitted earlier, to prevent duplicate call to connection_gone
99+
self.connection_gone("close");
100+
}
98101
});
99102

100103
this.stream.on("end", function () {
101104
self.connection_gone("end");
102105
});
103106

107+
if(this.options.socket_timeout){
108+
this.stream.setTimeout(this.options.socket_timeout, function () {
109+
self.stream.destroy();
110+
});
111+
}
112+
104113
this.stream.on("drain", function () {
105114
self.should_buffer = false;
106115
self.emit("drain");
@@ -824,12 +833,16 @@ RedisClient.prototype.pub_sub_command = function (command_obj) {
824833
};
825834

826835
RedisClient.prototype.end = function () {
827-
this.stream._events = {};
828836
this.connected = false;
829837
this.ready = false;
830838
this.closing = true;
831839
clearTimeout(this.retry_timer);
832-
return this.stream.end();
840+
if(this.stream){
841+
this.stream._events = {};
842+
if(this.stream.end){
843+
this.stream.end();
844+
}
845+
}
833846
};
834847

835848
function Multi(client, args) {
@@ -886,9 +899,9 @@ commands.forEach(function (command) {
886899

887900
// store db in this.select_db to restore it on reconnect
888901
RedisClient.prototype.select = function (db, callback) {
889-
var self = this;
902+
var self = this;
890903

891-
this.send_command('select', [db], function (err, res) {
904+
this.send_command('select', [db], function (err, res) {
892905
if (err === null) {
893906
self.selected_db = db;
894907
}
@@ -1122,4 +1135,4 @@ exports.print = function (err, reply) {
11221135
} else {
11231136
console.log("Reply: " + reply);
11241137
}
1125-
};
1138+
};

0 commit comments

Comments
 (0)