forked from knowthen/rtsupportclient
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocket.js
37 lines (35 loc) · 788 Bytes
/
socket.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
import { EventEmitter } from 'events';
class Socket {
constructor(ws = new WebSocket(), ee = new EventEmitter()) {
this.ws = ws;
this.ee = ee;
ws.onmessage = this.message.bind(this);
ws.onopen = this.open.bind(this);
ws.onclose = this.close.bind(this);
}
on(name, fn) {
this.ee.on(name, fn);
}
off(name, fn) {
this.ee.removeListener(name, fn);
}
emit(name, data) {
const message = JSON.stringify({ name, data });
this.ws.send(message);
}
message(e) {
try {
const message = JSON.parse(e.data);
this.ee.emit(message.name, message.data);
} catch (err) {
this.ee.emit('error', err);
}
}
open() {
this.ee.emit('connect');
}
close() {
this.ee.emit('disconnect');
}
}
export default Socket;