@@ -44,8 +44,11 @@ export class Socket extends EventEmitter<
4444 private readonly opts : ServerOptions ;
4545 private upgradeState : UpgradeState = "not_upgraded" ;
4646 private writeBuffer : Packet [ ] = [ ] ;
47- private pingIntervalTimerId ?: NodeJS . Timeout ;
48- private pingTimeoutTimerId ?: NodeJS . Timeout ;
47+ /*
48+ * Note: using a single timer for all sockets seems to result in a higher CPU consumption than using one timer for each socket
49+ */
50+ private pingIntervalTimer ?: Timer ;
51+ private pingTimeoutTimer ?: Timer ;
4952
5053 constructor ( id : string , opts : ServerOptions , transport : Transport ) {
5154 super ( ) ;
@@ -101,7 +104,7 @@ export class Socket extends EventEmitter<
101104 case "pong" :
102105 debug ( "got pong" ) ;
103106
104- clearTimeout ( this . pingTimeoutTimerId ) ;
107+ clearTimeout ( this . pingTimeoutTimer ) ;
105108 this . schedulePing ( ) ;
106109
107110 this . emitReserved ( "heartbeat" ) ;
@@ -136,7 +139,11 @@ export class Socket extends EventEmitter<
136139 * @private
137140 */
138141 private schedulePing ( ) {
139- this . pingIntervalTimerId = setTimeout ( ( ) => {
142+ if ( this . pingTimeoutTimer ) {
143+ this . pingIntervalTimer ?. refresh ( ) ;
144+ return ;
145+ }
146+ this . pingIntervalTimer = setTimeout ( ( ) => {
140147 debug (
141148 `writing ping packet - expecting pong within ${ this . opts . pingTimeout } ms` ,
142149 ) ;
@@ -151,11 +158,9 @@ export class Socket extends EventEmitter<
151158 * @private
152159 */
153160 private resetPingTimeout ( ) {
154- clearTimeout ( this . pingTimeoutTimerId ) ;
155- this . pingTimeoutTimerId = setTimeout ( ( ) => {
156- if ( this . readyState !== "closed" ) {
157- this . onClose ( "ping timeout" ) ;
158- }
161+ clearTimeout ( this . pingTimeoutTimer ) ;
162+ this . pingTimeoutTimer = setTimeout ( ( ) => {
163+ this . onClose ( "ping timeout" ) ;
159164 } , this . opts . pingTimeout ) ;
160165 }
161166
@@ -259,8 +264,8 @@ export class Socket extends EventEmitter<
259264 debug ( `socket closed due to ${ reason } ` ) ;
260265
261266 this . readyState = "closed" ;
262- clearTimeout ( this . pingIntervalTimerId ) ;
263- clearTimeout ( this . pingTimeoutTimerId ) ;
267+ clearTimeout ( this . pingIntervalTimer ) ;
268+ clearTimeout ( this . pingTimeoutTimer ) ;
264269
265270 this . closeTransport ( ) ;
266271 this . emitReserved ( "close" , reason ) ;
0 commit comments