Skip to content

Commit 0aa62f2

Browse files
authored
Make tcp-keepalive configurable (brianc#1058)
1 parent ad65c7b commit 0aa62f2

File tree

3 files changed

+25
-10
lines changed

3 files changed

+25
-10
lines changed

lib/client.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@ var Client = function(config) {
2525

2626
this.connection = c.connection || new Connection({
2727
stream: c.stream,
28-
ssl: this.connectionParameters.ssl
28+
ssl: this.connectionParameters.ssl,
29+
keepAlive: c.keepAlive || false
2930
});
3031
this.queryQueue = [];
3132
this.binary = c.binary || defaults.binary;

lib/connection.js

+4-1
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ var Connection = function(config) {
1111
EventEmitter.call(this);
1212
config = config || {};
1313
this.stream = config.stream || new net.Stream();
14+
this._keepAlive = config.keepAlive;
1415
this.lastBuffer = false;
1516
this.lastOffset = 0;
1617
this.buffer = null;
@@ -47,8 +48,10 @@ Connection.prototype.connect = function(port, host) {
4748
var self = this;
4849

4950
this.stream.on('connect', function() {
51+
if (self._keepAlive) {
52+
self.stream.setKeepAlive(true);
53+
}
5054
self.emit('connect');
51-
self.stream.setKeepAlive(true);
5255
});
5356

5457
this.stream.on('error', function(error) {

test/unit/connection/startup-tests.js

+19-8
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,18 @@ test('connection can take existing stream', function() {
77
});
88

99
test('using closed stream', function() {
10-
var stream = new MemoryStream();
11-
stream.readyState = 'closed';
12-
stream.connect = function(port, host) {
13-
this.connectCalled = true;
14-
this.port = port;
15-
this.host = host;
16-
}
10+
var makeStream = function() {
11+
var stream = new MemoryStream();
12+
stream.readyState = 'closed';
13+
stream.connect = function(port, host) {
14+
this.connectCalled = true;
15+
this.port = port;
16+
this.host = host;
17+
}
18+
return stream;
19+
};
20+
21+
var stream = makeStream();
1722

1823
var con = new Connection({stream: stream});
1924

@@ -46,14 +51,20 @@ test('using closed stream', function() {
4651

4752
test('after stream emits connected event init TCP-keepalive', function() {
4853

54+
var stream = makeStream();
55+
var con = new Connection({ stream: stream, keepAlive: true });
56+
con.connect(123, 'test');
57+
4958
var res = false;
5059

5160
stream.setKeepAlive = function(bit) {
5261
res = bit;
5362
};
5463

5564
assert.ok(stream.emit('connect'));
56-
assert.equal(res, true);
65+
setTimeout(function() {
66+
assert.equal(res, true);
67+
})
5768
});
5869
});
5970

0 commit comments

Comments
 (0)