@@ -39,6 +39,7 @@ export class Channel extends EventEmitter {
39
39
40
40
private outbound : Writable
41
41
private inbound : Writable
42
+ private listened = false
42
43
43
44
private enableCompression = false
44
45
private compressionThreshold = - 1
@@ -65,10 +66,10 @@ export class Channel extends EventEmitter {
65
66
}
66
67
67
68
/**
68
- * Is the connection ready to read and write
69
- */
69
+ * Is the connection ready to read and write
70
+ */
70
71
get ready ( ) {
71
- return this . connection . readable && this . connection . writable
72
+ return this . connection . readable && this . connection . writable && this . listened
72
73
}
73
74
74
75
findCoderById ( packetId : number , side : Side ) : Coder < any > {
@@ -117,12 +118,14 @@ export class Channel extends EventEmitter {
117
118
this . connection . on ( 'error' , ( e ) => { this . emit ( 'error' , e ) } )
118
119
119
120
this . emit ( 'listen' )
121
+ this . listened = true
120
122
}
121
123
122
124
disconnect ( ) {
123
- if ( ! this . ready ) {
125
+ if ( ! this . listened || ! this . ready ) {
124
126
return Promise . resolve ( )
125
127
}
128
+ this . listened = false
126
129
return new Promise < void > ( ( resolve , reject ) => {
127
130
this . connection . once ( 'close' , ( err ) => {
128
131
if ( err ) {
@@ -141,8 +144,16 @@ export class Channel extends EventEmitter {
141
144
send < T > ( message : T , skeleton ?: Partial < T > ) {
142
145
if ( ! this . connection . writable ) { throw new Error ( "Cannot write if the connection isn't writable!" ) }
143
146
if ( skeleton ) { Object . assign ( ( message as any ) , skeleton ) }
144
- this . outbound . write ( message )
145
- this . emit ( 'send' , message )
147
+ return new Promise < void > ( ( resolve , reject ) => {
148
+ this . outbound . write ( message , ( err ) => {
149
+ if ( err ) {
150
+ reject ( err )
151
+ } else {
152
+ this . emit ( 'send' , message )
153
+ resolve ( )
154
+ }
155
+ } )
156
+ } )
146
157
}
147
158
148
159
/**
0 commit comments