forked from jbmusso/gremlin-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebSocketGremlinConnection.js
More file actions
55 lines (43 loc) · 1.15 KB
/
WebSocketGremlinConnection.js
File metadata and controls
55 lines (43 loc) · 1.15 KB
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
import { EventEmitter } from 'events';
import WebSocket from 'ws';
export default class WebSocketGremlinConnection extends EventEmitter {
constructor({ port, host, path, ssl, rejectUnauthorized }) {
super();
this.open = false;
const address = `ws${ssl ? 's' : ''}://${host}:${port}${path}`;
const options = {
rejectUnauthorized
};
this.ws = new WebSocket(address, null, options);
this.ws.onopen = () => this.onOpen();
this.ws.onerror = (err) => this.handleError(err);
this.ws.onmessage = (message) => this.handleMessage(message);
this.ws.onclose = (event) => this.onClose(event);
this.ws.binaryType = "arraybuffer";
}
onOpen() {
this.open = true;
this.emit('open');
}
handleError(err) {
this.emit('error', err);
}
handleMessage(message) {
this.emit('message', message);
}
onClose(event) {
this.open = false;
this.emit('close', event);
}
terminate() {
this.open = false;
this.ws.close();
}
sendMessage(message) {
this.ws.send(message, { mask: true, binary: true }, (err) => {
if (err) {
this.handleError(err);
}
});
}
}