Skip to content

Commit 5493e58

Browse files
authored
Merge pull request #2 from HoshenKadosh/master
Socket Heartbeat Implementation (From: MatthieuLemoine#61)
2 parents 87406ac + b744526 commit 5493e58

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

src/client.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,14 @@ const {
1010
kLoginRequestTag,
1111
kDataMessageStanzaTag,
1212
kLoginResponseTag,
13+
kHeartbeatPingTag
1314
} = require('./constants');
1415
const { load } = require('protobufjs');
1516

1617
const HOST = 'mtalk.google.com';
1718
const PORT = 5228;
1819
const MAX_RETRY_TIMEOUT = 15;
20+
const HEARTBEAT_INTERVAL = 10;
1921

2022
let proto = null;
2123

@@ -78,8 +80,32 @@ module.exports = class Client extends EventEmitter {
7880
this._socket.write(this._loginBuffer());
7981
}
8082

83+
_startHeartBeats(){
84+
//every X min send a heartbeat to prevent socket disconnection
85+
const intervalMS = HEARTBEAT_INTERVAL * 60 * 1000;
86+
const hbBuffer = this._heartBeatBuffer();
87+
88+
this._heartBeatsInterval = setInterval(function(){
89+
if (!this._socket) return clearInterval(this._heartBeatsInterval);
90+
this._socket.write(hbBuffer);
91+
}.bind(this), intervalMS);
92+
}
93+
94+
_heartBeatBuffer(){
95+
const heartBeatType = proto.lookupType('mcs_proto.HeartbeatPing');
96+
const heartBeat = {};
97+
98+
const buffer = heartBeatType.encodeDelimited(heartBeat).finish();
99+
100+
return Buffer.concat([
101+
Buffer.from([kHeartbeatPingTag]),
102+
buffer,
103+
]);
104+
}
105+
81106
_destroy() {
82107
clearTimeout(this._retryTimeout);
108+
clearInterval(this._heartBeatsInterval)
83109
if (this._socket) {
84110
this._socket.removeListener('connect', this._onSocketConnect);
85111
this._socket.removeListener('close', this._onSocketClose);
@@ -132,10 +158,12 @@ module.exports = class Client extends EventEmitter {
132158

133159
_onSocketConnect() {
134160
this._retryCount = 0;
161+
this._startHeartBeats()
135162
this.emit('connect');
136163
}
137164

138165
_onSocketClose() {
166+
clearInterval(this._heartBeatsInterval)
139167
this.emit('disconnect')
140168
this._retry();
141169
}

0 commit comments

Comments
 (0)