forked from ivanseidel/node-ssl-vision
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.js
78 lines (60 loc) · 1.59 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 dgram = require('dgram')
const EventEmitter = require('events')
const proto = require('./proto')
module.exports = class SSLClient extends EventEmitter {
constructor(HOST, PORT) {
super()
this.HOST = HOST || '224.5.23.3'
this.PORT = PORT || 10002
this.client = null
// Public state variables
this.data = null
// Construct parser
this.proto = proto
}
connect () {
return new Promise((resolve, reject) => {
if (this.client) {
throw new Error('Client is already open. Close the connection first')
}
// Create Client
this.client = dgram.createSocket('udp4')
// Bind message
this._bind()
// Wait to bind
this.client.bind(this.PORT, this.HOST, () => {
// Initialize connection
this._init()
// Resolve
resolve()
})
})
}
_init() {
var address = this.client.address()
this.client.setBroadcast(true)
this.client.setMulticastTTL(128)
this.client.addMembership(this.HOST)
}
_bind() {
this.client.on('message', this._message.bind(this))
}
_message(data, remote) {
try {
this.data = proto.SSL_WrapperPacket.decode(data)
// Skip if frame is null
if (!this.data)
return
// Emit data
this.emit('data', this.data)
// Emit detection only if set
if (this.data.detection)
this.emit('detection', this.data.detection)
// Emit geometry only if set
if (this.data.geometry)
this.emit('geometry', this.data.geometry)
} catch (e) {
this.emit('error', e)
}
}
}