Skip to content

Commit 0904156

Browse files
committed
refactor: Add listen state to channel
1 parent eeed4a2 commit 0904156

File tree

2 files changed

+22
-11
lines changed

2 files changed

+22
-11
lines changed

packages/client/channel.ts

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ export class Channel extends EventEmitter {
3939

4040
private outbound: Writable
4141
private inbound: Writable
42+
private listened = false
4243

4344
private enableCompression = false
4445
private compressionThreshold = -1
@@ -65,10 +66,10 @@ export class Channel extends EventEmitter {
6566
}
6667

6768
/**
68-
* Is the connection ready to read and write
69-
*/
69+
* Is the connection ready to read and write
70+
*/
7071
get ready() {
71-
return this.connection.readable && this.connection.writable
72+
return this.connection.readable && this.connection.writable && this.listened
7273
}
7374

7475
findCoderById(packetId: number, side: Side): Coder<any> {
@@ -117,12 +118,14 @@ export class Channel extends EventEmitter {
117118
this.connection.on('error', (e) => { this.emit('error', e) })
118119

119120
this.emit('listen')
121+
this.listened = true
120122
}
121123

122124
disconnect() {
123-
if (!this.ready) {
125+
if (!this.listened || !this.ready) {
124126
return Promise.resolve()
125127
}
128+
this.listened = false
126129
return new Promise<void>((resolve, reject) => {
127130
this.connection.once('close', (err) => {
128131
if (err) {
@@ -141,8 +144,16 @@ export class Channel extends EventEmitter {
141144
send<T>(message: T, skeleton?: Partial<T>) {
142145
if (!this.connection.writable) { throw new Error("Cannot write if the connection isn't writable!") }
143146
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+
})
146157
}
147158

148159
/**

packages/client/status.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,13 +35,13 @@ export interface Status {
3535
*/
3636
version: {
3737
/**
38-
* The name of the version, might be standard version, like 1.14.4.
39-
* Or it can be modified content, just be any string the server hoster like.
40-
*/
38+
* The name of the version, might be standard version, like 1.14.4.
39+
* Or it can be modified content, just be any string the server hoster like.
40+
*/
4141
name: string
4242
/**
43-
* The protocol version
44-
*/
43+
* The protocol version
44+
*/
4545
protocol: number
4646
}
4747
/**

0 commit comments

Comments
 (0)