2023-05-19 16:28:12 +00:00
|
|
|
import { Observable } from 'rxjs';
|
|
|
|
|
|
|
|
export function createWebSocket<T>(
|
|
|
|
host: string,
|
|
|
|
wsPort: number,
|
|
|
|
deserialize: (input: string) => T,
|
|
|
|
endpoint = ''
|
|
|
|
): Observable<T> {
|
|
|
|
return new Observable((observer) => {
|
2024-10-20 11:12:18 +00:00
|
|
|
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
2024-10-23 07:07:42 +00:00
|
|
|
const ws = new WebSocket(`${protocol}//${host}:${wsPort}/${endpoint}`);
|
2023-05-19 16:28:12 +00:00
|
|
|
ws.onmessage = (e) => {
|
|
|
|
const reader = new FileReader();
|
|
|
|
reader.onload = () => {
|
|
|
|
const data = deserialize(JSON.parse(reader.result as string));
|
|
|
|
observer.next(data);
|
|
|
|
};
|
|
|
|
reader.readAsText(e.data);
|
|
|
|
};
|
|
|
|
ws.onerror = () => {
|
|
|
|
observer.error();
|
|
|
|
};
|
|
|
|
ws.onclose = () => {
|
|
|
|
observer.complete();
|
|
|
|
};
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
// Removing listeners to avoid loop
|
|
|
|
ws.onmessage = null;
|
|
|
|
ws.onclose = null;
|
|
|
|
ws.onerror = null;
|
|
|
|
ws.close();
|
|
|
|
};
|
|
|
|
});
|
|
|
|
}
|