@@ -45,27 +45,14 @@ class Agent extends DispatcherBase {
4545 }
4646
4747 this [ kOnConnect ] = ( origin , targets ) => {
48- const result = this [ kClients ] . get ( origin )
49- if ( result ) {
50- result . count += 1
51- }
5248 this . emit ( 'connect' , origin , [ this , ...targets ] )
5349 }
5450
5551 this [ kOnDisconnect ] = ( origin , targets , err ) => {
56- const result = this [ kClients ] . get ( origin )
57- if ( result ) {
58- result . count -= 1
59- if ( result . count <= 0 ) {
60- this [ kClients ] . delete ( origin )
61- result . dispatcher . destroy ( )
62- }
63- }
6452 this . emit ( 'disconnect' , origin , [ this , ...targets ] , err )
6553 }
6654
6755 this [ kOnConnectionError ] = ( origin , targets , err ) => {
68- // TODO: should this decrement result.count here?
6956 this . emit ( 'connectionError' , origin , [ this , ...targets ] , err )
7057 }
7158 }
@@ -89,11 +76,33 @@ class Agent extends DispatcherBase {
8976 const result = this [ kClients ] . get ( key )
9077 let dispatcher = result && result . dispatcher
9178 if ( ! dispatcher ) {
79+ const closeClientIfUnused = ( connected ) => {
80+ const result = this [ kClients ] . get ( key )
81+ if ( result ) {
82+ if ( connected ) result . count -= 1
83+ if ( result . count <= 0 ) {
84+ this [ kClients ] . delete ( key )
85+ result . dispatcher . close ( )
86+ }
87+ }
88+ }
9289 dispatcher = this [ kFactory ] ( opts . origin , this [ kOptions ] )
9390 . on ( 'drain' , this [ kOnDrain ] )
94- . on ( 'connect' , this [ kOnConnect ] )
95- . on ( 'disconnect' , this [ kOnDisconnect ] )
96- . on ( 'connectionError' , this [ kOnConnectionError ] )
91+ . on ( 'connect' , ( origin , targets ) => {
92+ const result = this [ kClients ] . get ( key )
93+ if ( result ) {
94+ result . count += 1
95+ }
96+ this [ kOnConnect ] ( origin , targets )
97+ } )
98+ . on ( 'disconnect' , ( origin , targets , err ) => {
99+ closeClientIfUnused ( true )
100+ this [ kOnDisconnect ] ( origin , targets , err )
101+ } )
102+ . on ( 'connectionError' , ( origin , targets , err ) => {
103+ closeClientIfUnused ( false )
104+ this [ kOnConnectionError ] ( origin , targets , err )
105+ } )
97106
98107 this [ kClients ] . set ( key , { count : 0 , dispatcher } )
99108 }
0 commit comments