-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathsocket.js
More file actions
38 lines (36 loc) · 777 Bytes
/
socket.js
File metadata and controls
38 lines (36 loc) · 777 Bytes
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
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;