1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- class Socket {
- constructor(path) {
- const url = this.url = new Url();
-
- if(url.getProtocol() === 'https:')
- url.setProtocol('wss');
- else
- url.setProtocol('ws');
- url.setPath(path).setHash();
- try {
- this.connection = new WebSocket(url.toString());
-
- this.keepAlive = setInterval(() => {
- this.connection.send('keep-alive');
- }, 20000);
-
- this.connection.onclose = (e) => {
- clearInterval(this.keepAlive);
- };
- } catch(e) {
- this.connection = null;
- }
- }
- onOpen(onopen) {
- if(this.connection)
- this.connection.onopen = onopen;
- return this;
- }
- onMessage(onmessage) {
- if(this.connection)
- this.connection.onmessage = onmessage;
- return this;
- }
- onError(onerror) {
- if(this.connection)
- this.connection.onerror = onerror;
- return this;
- }
- onClose(onclose) {
- if(this.connection)
- this.connection.onclose = (e) => {
- clearInterval(this.keepAlive);
- onclose(e);
- };
- return this;
- }
- }
|