@@ -95,6 +95,8 @@ export class StdioClientTransport implements Transport {
9595 private _readBuffer : ReadBuffer = new ReadBuffer ( ) ;
9696 private _serverParams : StdioServerParameters ;
9797 private _stderrStream : PassThrough | null = null ;
98+ private _onServerDataHandler ?: ( chunk : Buffer ) => void ;
99+ private _onServerErrorHandler ?: ( error : Error ) => void ;
98100
99101 onclose ?: ( ) => void ;
100102 onerror ?: ( error : Error ) => void ;
@@ -130,33 +132,31 @@ export class StdioClientTransport implements Transport {
130132 cwd : this . _serverParams . cwd
131133 } ) ;
132134
135+ this . _onServerDataHandler = ( chunk : Buffer ) => {
136+ this . _readBuffer . append ( chunk ) ;
137+ this . processReadBuffer ( ) ;
138+ } ;
139+ this . _onServerErrorHandler = ( error : Error ) => {
140+ this . onerror ?.( error ) ;
141+ } ;
142+
143+ this . _process . stdout ?. on ( 'data' , this . _onServerDataHandler ) ;
144+ this . _process . stdout ?. on ( 'error' , this . _onServerErrorHandler ) ;
145+ this . _process . stdin ?. on ( 'error' , this . _onServerErrorHandler ) ;
146+
133147 this . _process . on ( 'error' , error => {
134148 reject ( error ) ;
135149 this . onerror ?.( error ) ;
136150 } ) ;
137-
138- this . _process . on ( 'spawn' , ( ) => {
139- resolve ( ) ;
140- } ) ;
141-
142- this . _process . on ( 'close' , _code => {
151+ this . _process . once ( 'spawn' , ( ) => resolve ( ) ) ;
152+ this . _process . once ( 'close' , _code => {
153+ if ( this . _process ) {
154+ this . cleanupListeners ( this . _process ) ;
155+ }
143156 this . _process = undefined ;
144157 this . onclose ?.( ) ;
145158 } ) ;
146159
147- this . _process . stdin ?. on ( 'error' , error => {
148- this . onerror ?.( error ) ;
149- } ) ;
150-
151- this . _process . stdout ?. on ( 'data' , chunk => {
152- this . _readBuffer . append ( chunk ) ;
153- this . processReadBuffer ( ) ;
154- } ) ;
155-
156- this . _process . stdout ?. on ( 'error' , error => {
157- this . onerror ?.( error ) ;
158- } ) ;
159-
160160 if ( this . _stderrStream && this . _process . stderr ) {
161161 this . _process . stderr . pipe ( this . _stderrStream ) ;
162162 }
@@ -202,8 +202,19 @@ export class StdioClientTransport implements Transport {
202202 }
203203 }
204204
205+ private cleanupListeners ( process : ChildProcess ) {
206+ if ( this . _onServerDataHandler ) {
207+ process . stdout ?. off ( 'data' , this . _onServerDataHandler ) ;
208+ }
209+ if ( this . _onServerErrorHandler ) {
210+ process . stdout ?. off ( 'error' , this . _onServerErrorHandler ) ;
211+ process . stdin ?. off ( 'error' , this . _onServerErrorHandler ) ;
212+ }
213+ }
214+
205215 async close ( ) : Promise < void > {
206216 if ( this . _process ) {
217+ this . cleanupListeners ( this . _process ) ;
207218 const processToClose = this . _process ;
208219 this . _process = undefined ;
209220
0 commit comments