-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathbuffered-socket.ts
63 lines (51 loc) · 1.48 KB
/
buffered-socket.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import type {Socket, SocketDelegate, StableSocket} from './stable-socket'
import {isFatal} from './stable-socket'
export class BufferedSocket implements Socket, SocketDelegate {
private buf: string[] = []
private socket: Socket
private delegate: SocketDelegate
constructor(socket: StableSocket) {
this.socket = socket
this.delegate = socket.delegate
socket.delegate = this
}
open(): Promise<void> {
return this.socket.open()
}
close(code?: number, reason?: string): void {
this.socket.close(code, reason)
}
send(data: string): void {
if (this.socket.isOpen()) {
this.flush()
this.socket.send(data)
} else {
this.buf.push(data)
}
}
isOpen(): boolean {
return this.socket.isOpen()
}
flush(): void {
for (const data of this.buf) {
this.socket.send(data)
}
this.buf.length = 0
}
socketDidOpen(socket: Socket): void {
this.flush()
this.delegate.socketDidOpen(socket)
}
socketDidClose(socket: Socket, code?: number, reason?: string): void {
this.delegate.socketDidClose(socket, code, reason)
}
socketDidFinish(socket: Socket): void {
this.delegate.socketDidFinish(socket)
}
socketDidReceiveMessage(socket: Socket, message: string): void {
this.delegate.socketDidReceiveMessage(socket, message)
}
socketShouldRetry(socket: Socket, code: number): boolean {
return this.delegate.socketShouldRetry ? this.delegate.socketShouldRetry(socket, code) : !isFatal(code)
}
}