@@ -30,6 +30,9 @@ Transport = function(ua, server) {
3030 this . reconnectTimer = null ;
3131 this . lastTransportError = { } ;
3232
33+ this . keepAliveInterval = ua . configuration . keepAliveInterval ;
34+ this . keepAliveTimer = null ;
35+
3336 this . ua . transport = this ;
3437
3538 // Connect
@@ -57,6 +60,38 @@ Transport.prototype = {
5760 }
5861 } ,
5962
63+ /**
64+ * Send a keep-alive (a double-CRLF sequence).
65+ * @private
66+ * @returns {Boolean }
67+ */
68+ sendKeepAlive : function ( ) {
69+ return this . send ( '\r\n\r\n' ) ;
70+ } ,
71+
72+ /**
73+ * Start sending keep-alives.
74+ * @private
75+ */
76+ startSendingKeepAlives : function ( ) {
77+ if ( this . keepAliveInterval && ! this . keepAliveTimer ) {
78+ this . keepAliveTimer = SIP . Timers . setTimeout ( function ( ) {
79+ this . sendKeepAlive ( ) ;
80+ this . keepAliveTimer = null ;
81+ this . startSendingKeepAlives ( ) ;
82+ } . bind ( this ) , computeKeepAliveTimeout ( this . keepAliveInterval ) ) ;
83+ }
84+ } ,
85+
86+ /**
87+ * Stop sending keep-alives.
88+ * @private
89+ */
90+ stopSendingKeepAlives : function ( ) {
91+ SIP . Timers . clearTimeout ( this . keepAliveTimer ) ;
92+ this . keepAliveTimer = null ;
93+ } ,
94+
6095 /**
6196 * Disconnect socket.
6297 */
@@ -65,6 +100,8 @@ Transport.prototype = {
65100 // Clear reconnectTimer
66101 SIP . Timers . clearTimeout ( this . reconnectTimer ) ;
67102
103+ this . stopSendingKeepAlives ( ) ;
104+
68105 this . closed = true ;
69106 this . logger . log ( 'closing WebSocket ' + this . server . ws_uri ) ;
70107 this . ws . close ( ) ;
@@ -146,6 +183,8 @@ Transport.prototype = {
146183 this . closed = false ;
147184 // Trigger onTransportConnected callback
148185 this . ua . onTransportConnected ( this ) ;
186+ // Start sending keep-alives
187+ this . startSendingKeepAlives ( ) ;
149188 } ,
150189
151190 /**
@@ -158,6 +197,8 @@ Transport.prototype = {
158197 this . lastTransportError . code = e . code ;
159198 this . lastTransportError . reason = e . reason ;
160199
200+ this . stopSendingKeepAlives ( ) ;
201+
161202 if ( this . reconnection_attempts > 0 ) {
162203 this . logger . log ( 'Reconnection attempt ' + this . reconnection_attempts + ' failed (code: ' + e . code + ( e . reason ? '| reason: ' + e . reason : '' ) + ')' ) ;
163204 this . reconnect ( ) ;
@@ -302,6 +343,16 @@ Transport.prototype = {
302343 }
303344} ;
304345
346+ /**
347+ * Compute an amount of time in seconds to wait before sending another
348+ * keep-alive.
349+ * @returns {Number }
350+ */
351+ function computeKeepAliveTimeout ( upperBound ) {
352+ var lowerBound = upperBound * 0.8 ;
353+ return 1000 * ( Math . random ( ) * ( upperBound - lowerBound ) + lowerBound ) ;
354+ }
355+
305356Transport . C = C ;
306357return Transport ;
307358} ;
0 commit comments