66 lines
1.0 KiB
JavaScript
66 lines
1.0 KiB
JavaScript
import Emitter from 'tiny-emitter'
|
|
import inherits from 'util.inherits';
|
|
|
|
function WS(url) {
|
|
Emitter.call(this);
|
|
|
|
this.url = url;
|
|
this.connected = false;
|
|
|
|
this.connect();
|
|
}
|
|
|
|
WS.prototype = {
|
|
connect: function() {
|
|
try {
|
|
this.ws = new WebSocket(this.url);
|
|
} catch (e) {
|
|
this.reconnect();
|
|
return;
|
|
}
|
|
|
|
this.ws.onopen = this.onopen.bind(this);
|
|
this.ws.onclose = this.onclose.bind(this);
|
|
this.ws.onmessage = this.onmessage.bind(this);
|
|
},
|
|
|
|
reconnect: function() {
|
|
setTimeout(this.connect.bind(this), 5000);
|
|
},
|
|
|
|
close: function() {
|
|
this.closed = true;
|
|
|
|
this.ws.close();
|
|
},
|
|
|
|
onopen: function() {
|
|
this.connected = true;
|
|
this.emit('connect');
|
|
},
|
|
|
|
onclose: function() {
|
|
this.emit('close');
|
|
|
|
this.connected = false;
|
|
|
|
if (!this.closed) {
|
|
this.reconnect();
|
|
}
|
|
},
|
|
|
|
onmessage: function(data) {
|
|
try {
|
|
let object = JSON.parse(data.data);
|
|
|
|
this.emit(object.name, object.data);
|
|
} catch(e) {
|
|
|
|
}
|
|
}
|
|
};
|
|
|
|
inherits(WS, Emitter);
|
|
|
|
export default WS;
|