-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.js
78 lines (55 loc) · 1.84 KB
/
client.js
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
const Datagram = require('dgram');
class AudioClient {
constructor(audioEngine) {
let reuseAddr = true;
let constr = this.constructor;
let errorCallback = constr.sockError.bind(this);
let outputCallback = constr.audioOutput.bind(this);
let inputCallback = constr.sockInput.bind(this);
let closeCallback = constr.sockDisconnect.bind(this);
let connectionCallback = constr.sockConn.bind(this);
let socket = Datagram.createSocket({
type: 'udp4', reuseAddr: reuseAddr
});
socket.on('error', errorCallback);
socket.on('message', inputCallback);
socket.on('close', closeCallback);
socket.on('connect', connectionCallback);
audioEngine.on('data', outputCallback);
this.socket = socket;
this.engine = audioEngine;
}
connect(host, port) {
this.socket.connect(port, host);
}
disconnect() {
this.socket.close();
}
static audioOutput(data) {
// NOTE: executed from within the context of a class instance.
this.socket.send(data);
}
static sockInput(data, info) {
// NOTE: executed from within the context of a class instance.
this.engine.write(data);
}
static sockConn() {
// NOTE: executed from within the context of a class instance.
let host = this.socket.address().address;
let port = this.socket.address().port;
this.engine.start();
console.log('CLIENT: connected to', host, 'via local port', port);
}
static sockDisconnect() {
// NOTE: executed from within the context of a class instance.
let host = this.socket.address().address;
let port = this.socket.address().port;
this.engine.quit();
console.log('CLIENT: diconnected to', host, 'via local port', port);
}
static sockError(err) {
// NOTE: executed from within the context of a class instance.
throw err;
}
}
module.exports = AudioClient;