-
Notifications
You must be signed in to change notification settings - Fork 3
/
RtcConnection.ts
81 lines (70 loc) · 1.78 KB
/
RtcConnection.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
79
80
81
export const rtcConfig = {
iceServers: [
{
username: "YOUR USERNAME",
urls: ["xxx.xirsys.com", "xxx.xirsys.com"],
credential: "",
},
],
};
export const createRTCConnection = () => {
let localConnection = new RTCPeerConnection(rtcConfig);
const createDataChannel = (label: string, id: number) =>
localConnection.createDataChannel(label, {
negotiated: true,
id,
});
const commandsChannel = createDataChannel("commandChannel", 0);
const negotiationChannel = createDataChannel("negotiationChannel", 2);
return {
localConnection,
channels: {
commandsChannel,
negotiationChannel,
},
};
};
export const setupConnection = (
webSocket: WebSocket,
connectionType: ConnectionType,
peerConnectionId: string
): ConnectionMeta => {
const connection = createLocalConnection(peerConnectionId, connectionType);
const { connection: localConnection, channels } = connection;
webSocket.onmessage = onMessageHandlerNegotiation(
connection,
peerConnectionId,
webSocket
);
localConnection.onicecandidate = onIceCandidateHandler(
peerConnectionId,
webSocket,
channels.negotiationChannel
);
localConnection.onnegotiationneeded = onNegotiationNeededHandler(
connection,
peerConnectionId,
webSocket
);
channels.negotiationChannel.onmessage = onMessageHandlerNegotiation(
connection,
peerConnectionId,
webSocket
);
return connection;
};
function createLocalConnection(
connectionId: string,
type: ConnectionType
): ConnectionMeta {
const { localConnection, channels } = createRTCConnection();
return {
type,
connectionId,
channels,
connection: localConnection,
makingOffer: false,
ignoreOffer: false,
isSettingRemoteAnswerPending: false,
};
}