-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathWebSocketClient.js
More file actions
42 lines (37 loc) · 838 Bytes
/
WebSocketClient.js
File metadata and controls
42 lines (37 loc) · 838 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { log } from "../utils/log.js";
/** @typedef {import("../index").EXPECTED_ANY} EXPECTED_ANY */
/**
* @implements {CommunicationClient}
*/
export default class WebSocketClient {
/**
* @param {string} url url to connect
*/
constructor(url) {
this.client = new WebSocket(url);
this.client.onerror = (error) => {
log.error(error);
};
}
/**
* @param {(...args: EXPECTED_ANY[]) => void} fn function
*/
onOpen(fn) {
this.client.onopen = fn;
}
/**
* @param {(...args: EXPECTED_ANY[]) => void} fn function
*/
onClose(fn) {
this.client.onclose = fn;
}
// call f with the message string as the first argument
/**
* @param {(...args: EXPECTED_ANY[]) => void} fn function
*/
onMessage(fn) {
this.client.onmessage = (err) => {
fn(err.data);
};
}
}