-
-
Save mikeyb/b03d05c058cf83955b142d4456f74eeb to your computer and use it in GitHub Desktop.
A websocket helper class written in typescript for use with angularjs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Utilities { | |
export class WebSocketHelper { | |
constructor(private $q: ng.IQService, private url: string, private connectionInterval = 5000) { | |
} | |
private wsPromise: ng.IPromise<WebSocket>; | |
private createWebSocket(): ng.IPromise<WebSocket> { | |
var d = this.$q.defer(); | |
try { | |
var ws = new WebSocket(this.url); | |
ws.onerror = (evt) => { | |
console.log(evt); | |
setTimeout(() => { | |
var newPromise = this.createWebSocket(); | |
d.resolve(newPromise); | |
}, this.connectionInterval); | |
}; | |
ws.onopen = (evt) => { | |
console.log(evt); | |
d.resolve(ws); | |
}; | |
} catch (e) { | |
setTimeout(() => { | |
var newPromise = this.createWebSocket(); | |
d.resolve(newPromise); | |
}, this.connectionInterval); | |
} | |
return d.promise; | |
} | |
public getWebSocket(): ng.IPromise<WebSocket> { | |
var d = this.$q.defer(); | |
if (this.wsPromise == null) { | |
this.wsPromise = this.createWebSocket(); | |
this.wsPromise.then((ws) => { | |
ws.onmessage = evt => { | |
this.onMessage(evt); | |
}; | |
ws.onclose = (evt) => { | |
console.log(evt); | |
setTimeout(() => { | |
this.wsPromise = null; | |
var newPromise = this.getWebSocket(); | |
newPromise.then((nws) => { | |
this.onReconnect(nws); | |
}); | |
}, this.connectionInterval); | |
}; | |
d.resolve(ws); | |
return ws; | |
}); | |
} else { | |
this.wsPromise.then((ws) => { | |
d.resolve(ws); | |
return ws; | |
}); | |
} | |
return d.promise; | |
} | |
public messageHandler; | |
private onMessage(evt) { | |
try { | |
this.messageHandler(evt); | |
} catch (e) { | |
console.log(e); | |
} | |
} | |
public reconnectHandler; | |
private onReconnect(ws) { | |
try { | |
this.reconnectHandler(ws); | |
} catch (e) { | |
console.log(e); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment