fchat-rising/chat/WebSocket.ts

47 lines
1.4 KiB
TypeScript
Raw Permalink Normal View History

2018-01-06 16:14:21 +00:00
import {WebSocketConnection} from '../fchat';
2020-07-05 17:43:27 +00:00
import log from 'electron-log'; //tslint:disable-line:match-default-export-name
2017-09-02 01:50:31 +00:00
export default class Socket implements WebSocketConnection {
2019-06-07 19:31:42 +00:00
static host = 'wss://chat.f-list.net/chat2';
2018-01-06 16:14:21 +00:00
private socket: WebSocket;
private lastHandler: Promise<void> = Promise.resolve();
2017-09-02 01:50:31 +00:00
constructor() {
this.socket = new WebSocket(Socket.host);
}
2019-01-03 17:38:17 +00:00
get readyState(): WebSocketConnection.ReadyState {
return this.socket.readyState;
}
2017-09-02 01:50:31 +00:00
close(): void {
2020-07-05 17:43:27 +00:00
log.debug('socket.close');
2017-09-02 01:50:31 +00:00
this.socket.close();
}
onMessage(handler: (message: string) => void): void {
2018-01-06 16:14:21 +00:00
this.socket.addEventListener('message', (e) => {
2018-08-10 16:59:37 +00:00
this.lastHandler = this.lastHandler.then(() => handler(<string>e.data), (err) => {
window.requestAnimationFrame(() => { throw err; });
handler(<string>e.data);
});
2018-01-06 16:14:21 +00:00
});
2017-09-02 01:50:31 +00:00
}
onOpen(handler: () => void): void {
this.socket.addEventListener('open', handler);
}
2020-06-30 16:46:38 +00:00
onClose(handler: (e: CloseEvent) => void): void {
2017-09-02 01:50:31 +00:00
this.socket.addEventListener('close', handler);
}
onError(handler: (error: Error) => void): void {
2018-04-11 19:17:58 +00:00
this.socket.addEventListener('error', () => handler(new Error()));
2017-09-02 01:50:31 +00:00
}
send(message: string): void {
this.socket.send(message);
}
2020-06-30 16:46:38 +00:00
}