Skip to content

Instantly share code, notes, and snippets.

@hmdhk
Created November 4, 2015 10:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hmdhk/1c336bec42edc8a6abc5 to your computer and use it in GitHub Desktop.
Save hmdhk/1c336bec42edc8a6abc5 to your computer and use it in GitHub Desktop.
A websocket helper class written in typescript for use with angularjs
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