-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSignalingChannel.ts
78 lines (65 loc) · 2.08 KB
/
SignalingChannel.ts
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
interface AntWebsocketResponse {
command: "publish" | "start" | "takeConfiguration" | "takeCandidate" | "stop" | "play",
streamId: string;
token?: string;
type?: "offer" | "answer";
sdp?: string;
candidate?: string;
label?: string;
id?: string;
}
type ChannelCallbackFn = (data?: AntWebsocketResponse) => void;
interface SignalingCallbacks {
onopen: () => void;
start: ChannelCallbackFn;
takeCandidate: ChannelCallbackFn;
takeConfiguration: ChannelCallbackFn;
stop: ChannelCallbackFn;
}
export class SignalingChannel {
private ws?: WebSocket;
private callbacks: SignalingCallbacks;
private isOpen: boolean = false;
private url: string;
isChannelOpen = () => {
return this.isOpen;
}
constructor(url: string, callbacks: SignalingCallbacks) {
this.url = url;
this.callbacks = callbacks
}
open = () => {
this.ws = new WebSocket(this.url);
this.ws.onopen = this.onopen
this.ws.onmessage = this.onmessage
this.ws.onerror = this.onerror
}
onopen = () => {
this.isOpen = true;
this.callbacks.onopen();
}
onmessage = (event: WebSocketMessageEvent) => {
const data = JSON.parse(event.data) as AntWebsocketResponse;
console.log("command:", data.command, "data: ", event.data);
if (data.command in this.callbacks) {
this.callbacks[data.command as keyof SignalingCallbacks](data);
}
}
onerror = (error: WebSocketErrorEvent) => {
console.warn(error);
}
onclose = () => {
console.info("websocket connection closed");
}
// Send json message to websocket signaling channel
// https://ant-media-docs.readthedocs.io/en/latest/WebRTC-Developers.html#webrtc-websocket-messaging-details
// signaling channel request (signaling details)
sendJSON = (data: AntWebsocketResponse) => {
this.ws?.send(JSON.stringify(data));
}
close = () => {
console.info("closing websocket connection");
this.ws?.close();
this.ws = undefined;
}
}