Last active
August 4, 2016 21:27
-
-
Save tlimpanont/3298f73ac3be08914c7823012343cb0e to your computer and use it in GitHub Desktop.
Angular2 WebSocket Class | Can connect to raw websocket url using engine.io-client and have the ability to reconnect it's self and emit connectivity status
This file contains hidden or 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
import { Component } from '@angular/core'; | |
import {WebSocketClient} from './websocket-client'; | |
@Component({ | |
selector: 'my-app', | |
template: '<h1>Websocket connectivity: <small>{{connectivity}}</small></h1>' | |
}) | |
export class AppComponent { | |
connectivity:string; | |
constructor() { | |
var wsClient = new WebSocketClient('wss://websocket-server-tlimpanont.c9users.io/'); | |
wsClient.message$.subscribe( (data:any) => { | |
console.log(data); | |
}); | |
wsClient.connectivity$.subscribe( (connectivity:string) => { | |
this.connectivity = connectivity; | |
}); | |
} | |
} |
This file contains hidden or 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
import { Observer, Observable, Subject } from 'rxjs/Rx'; | |
import {EventEmitter} from '@angular/core'; | |
const eio = require('engine.io-client'); | |
export class WebSocketClient { | |
public message$:Observable<any>; | |
public connectivity$ = new EventEmitter(); | |
constructor(public webSocketUrl:string) { | |
let connect$ = Observable.create(this.connect.bind(this)); | |
let connectionRetry$ = connect$.retryWhen((errorObs: Observable<any>) => errorObs.delay(2000)); | |
let result = connectionRetry$.do((socket: any) => { | |
return Observable.create((observer: Observer<any>) => { | |
socket.on('message', (data: any) => { | |
console.log(data); | |
observer.next(data); | |
}); | |
socket.on('error', (error: any) => { | |
console.log(error); | |
observer.error(data); | |
}); | |
return () => observer.complete(); | |
}).subscribe(); | |
}); | |
this.message$ = result.last(); | |
} | |
private connect(observer: Observer<any>) { | |
let socket = new eio.Socket(this.webSocketUrl); | |
socket.binaryType = 'blob'; | |
socket.on('open', () => { | |
console.log('open!') | |
observer.next(socket); | |
this.connectivity$.next('online'); | |
}); | |
socket.on('close', () => { | |
console.log('close!') | |
observer.error('close!'); | |
this.connectivity$.next('offline'); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment