2020-09-10 09:48:37 +01:00
|
|
|
import { Injectable } from '@angular/core';
|
2021-05-18 14:37:43 +01:00
|
|
|
import * as Rx from "rxjs/Rx";
|
2022-01-12 09:29:48 +01:00
|
|
|
import { Observable, Subject } from "rxjs/Rx";
|
2020-09-10 09:48:37 +01:00
|
|
|
|
|
|
|
|
@Injectable({
|
|
|
|
|
providedIn: 'root'
|
|
|
|
|
})
|
|
|
|
|
export class WebsocketService {
|
|
|
|
|
|
|
|
|
|
message = '';
|
2022-01-12 09:29:48 +01:00
|
|
|
public messages: Subject<any>;
|
2020-09-10 09:48:37 +01:00
|
|
|
currentUser = '';
|
2021-05-18 14:37:43 +01:00
|
|
|
private subject: Rx.Subject<MessageEvent>;
|
2020-09-10 09:48:37 +01:00
|
|
|
|
2022-01-11 12:12:45 +01:00
|
|
|
constructor() {
|
2022-04-28 09:32:27 +01:00
|
|
|
|
2022-01-11 12:12:45 +01:00
|
|
|
}
|
2020-09-10 09:48:37 +01:00
|
|
|
|
2021-05-18 14:37:43 +01:00
|
|
|
public connect(url): Rx.Subject<MessageEvent> {
|
|
|
|
|
if (!this.subject) {
|
|
|
|
|
this.subject = this.create(url);
|
2022-04-28 09:32:27 +01:00
|
|
|
|
2021-05-18 14:37:43 +01:00
|
|
|
}
|
|
|
|
|
return this.subject;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private create(url): Rx.Subject<MessageEvent> {
|
|
|
|
|
let ws = new WebSocket(url);
|
|
|
|
|
|
2022-04-28 09:32:27 +01:00
|
|
|
|
2021-07-26 09:44:11 +01:00
|
|
|
|
2021-05-19 09:37:43 +01:00
|
|
|
|
2021-05-18 14:37:43 +01:00
|
|
|
let observable = Rx.Observable.create((obs: Rx.Observer<MessageEvent>) => {
|
|
|
|
|
ws.onmessage = obs.next.bind(obs);
|
|
|
|
|
ws.onerror = obs.error.bind(obs);
|
|
|
|
|
ws.onclose = obs.complete.bind(obs);
|
|
|
|
|
return ws.close.bind(ws);
|
|
|
|
|
});
|
|
|
|
|
let observer = {
|
|
|
|
|
next: (data: Object) => {
|
|
|
|
|
if (ws.readyState === WebSocket.OPEN) {
|
|
|
|
|
ws.send(JSON.stringify(data));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
return Rx.Subject.create(observer, observable);
|
2020-09-10 09:48:37 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|