In past we used several angular2 websocket impelmentations but we wasn't happy with them, there was several problems using them. So we decided to try our fortune doing it by our own with RxJs.
This is our first try:
@Injectable()
export class WebSocketService{
public createWebsocket(url: string): Subject<MessageEvent> {
let socket = new WebSocket(url);
let observable = Observable.create(
(observer: Observer<MessageEvent>) => {
socket.onmessage = observer.next.bind(observer);
socket.onerror = observer.error.bind(observer);
socket.onclose = observer.complete.bind(observer);
return socket.close.bind(socket);
});
let observer = {
next: (data: Object) => {
if (socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify(data));
}
}
};
return Subject.create(observer, observable);
}
}
The socket is opened and working well for a while. After a few seconds the browser is closing the socket and I get an closing event on server side.
This is the closing reason we get on server site: [1006] WebSocket Read EOF
Does anyone can help? Or does anyone know how to use WebSocketSubject?