-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathraw.ts
81 lines (68 loc) · 2 KB
/
raw.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import { connect, Socket } from "net"
import { EventEmitter } from "events"
import { TeamSpeak } from "../../TeamSpeak"
import { TeamSpeakQuery } from "../TeamSpeakQuery"
export class ProtocolRAW extends EventEmitter implements TeamSpeakQuery.QueryProtocolInterface {
private socket: Socket
chunk: string = ""
constructor(config: TeamSpeak.ConnectionParams) {
super()
this.socket = connect({
port: config.queryport,
host: config.host,
localAddress: config.localAddress
})
this.socket.setEncoding("utf8")
this.socket.setTimeout(config.readyTimeout)
this.socket.on("timeout", this.handleTimeout.bind(this))
this.socket.on("connect", this.handleConnect.bind(this))
this.socket.on("data", this.handleData.bind(this))
this.socket.on("error", this.handleError.bind(this))
this.socket.on("close", this.handleClose.bind(this))
}
/**
* Called after the socket was not able to connect within the given timeframe
*/
private handleTimeout() {
this.socket.destroy()
this.emit("error", Error("Socket Timeout reached"))
}
/**
* Called after the Socket has been established
*/
private handleConnect() {
this.socket.setTimeout(0)
this.emit("connect")
}
/**
* called when the Socket emits an error
*/
private handleError(err: Error) {
this.emit("error", err)
}
/**
* called when the connection with the Socket gets closed
*/
private handleClose() {
this.emit("close", String(this.chunk))
}
/**
* called when the Socket receives data
* Splits the data with every newline
*/
private handleData(chunk: string) {
this.chunk += chunk
const lines = this.chunk.split("\n")
this.chunk = lines.pop() || ""
lines.forEach(line => this.emit("line", line))
}
send(str: string) {
this.socket.write(`${str}\n`)
}
sendKeepAlive() {
this.socket.write(" \n")
}
close() {
return this.socket.destroy()
}
}