@@ -10,12 +10,14 @@ const {
10
10
kLoginRequestTag,
11
11
kDataMessageStanzaTag,
12
12
kLoginResponseTag,
13
+ kHeartbeatPingTag
13
14
} = require ( './constants' ) ;
14
15
const { load } = require ( 'protobufjs' ) ;
15
16
16
17
const HOST = 'mtalk.google.com' ;
17
18
const PORT = 5228 ;
18
19
const MAX_RETRY_TIMEOUT = 15 ;
20
+ const HEARTBEAT_INTERVAL = 10 ;
19
21
20
22
let proto = null ;
21
23
@@ -78,8 +80,32 @@ module.exports = class Client extends EventEmitter {
78
80
this . _socket . write ( this . _loginBuffer ( ) ) ;
79
81
}
80
82
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
+
81
106
_destroy ( ) {
82
107
clearTimeout ( this . _retryTimeout ) ;
108
+ clearInterval ( this . _heartBeatsInterval )
83
109
if ( this . _socket ) {
84
110
this . _socket . removeListener ( 'connect' , this . _onSocketConnect ) ;
85
111
this . _socket . removeListener ( 'close' , this . _onSocketClose ) ;
@@ -132,10 +158,12 @@ module.exports = class Client extends EventEmitter {
132
158
133
159
_onSocketConnect ( ) {
134
160
this . _retryCount = 0 ;
161
+ this . _startHeartBeats ( )
135
162
this . emit ( 'connect' ) ;
136
163
}
137
164
138
165
_onSocketClose ( ) {
166
+ clearInterval ( this . _heartBeatsInterval )
139
167
this . emit ( 'disconnect' )
140
168
this . _retry ( ) ;
141
169
}
0 commit comments