forked from mitxela/webrtc-pong
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DC.js
111 lines (94 loc) · 2.84 KB
/
DC.js
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
const DC={id:null, dc:null, me:null, you:null, log:function(){}};
(function(){
URL='signal.php';
let oldId = window.location.hash.match(/^#([1-9]\d{3})$/);
if (oldId) DC.id = oldId[1];
var cfg = {
'iceServers': [
{'urls': 'stun:stun.stunprotocol.org:3478'},
{'urls': 'stun:stun.l.google.com:19302'},
]
};
var pc=null;
function post(data, callback){
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if(ajax.readyState==4 && ajax.status==200){
callback(JSON.parse(ajax.responseText))
}
}
ajax.open("POST", URL);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.send(data);
}
function init() {
pc = new RTCPeerConnection(cfg)
pc.onicecandidate = function(e) {
if (e.candidate != null) {
DC.log("got ice candidate: ",e.candidate)
post("id="+DC.id+"&to="+DC.you+"&msg="+encodeURIComponent(JSON.stringify({"ice":e.candidate})), gotmsgs);
}
}
pc.onicegatheringstatechange = function(e){
if (e.target.iceGatheringState=="complete") {
function poll(){
post("to="+DC.you+"&id="+DC.id, function(d){
gotmsgs(d);
if (DC.me=='bob' && DC.dc.readyState=="connecting") setTimeout(poll, 1000);
})
}
setTimeout(poll, 1000);
}
}
window.location.assign('#'+DC.id)
}
function gotmsgs(d){
for (c of d.msgs) {
if (c.ice) {
pc.addIceCandidate(new RTCIceCandidate(c.ice)).catch(DC.log)
}
if (c.sdp) {
gotsdp(c.sdp)
}
}
}
function gotsdp(sdp){
DC.log("got sdp",sdp)
pc.setRemoteDescription( new RTCSessionDescription(sdp)).then(function(){
if (sdp.type=='offer') pc.createAnswer().then(createdDesc).catch(DC.log)
});
}
function createdDesc(desc){
pc.setLocalDescription(desc).then(function(){
post("to="+DC.you+"&id="+DC.id+"&msg="+encodeURIComponent(JSON.stringify({"sdp":pc.localDescription})),gotmsgs)
}).catch(DC.log);
}
DC.host = function( setup, ready ) {
DC.me='bob';
DC.you='alice';
post("id="+DC.id, newId=> {
if (newId) DC.id = newId;
init()
DC.dc = pc.createDataChannel('test')
Object.assign(DC.dc, setup)
pc.createOffer().then(createdDesc).catch(DC.log)
ready(DC.id);
})
};
DC.join = function( joinid, setup ){
DC.me='alice';
DC.you='bob';
DC.id = joinid;
init();
pc.ondatachannel = function (e) {
DC.dc = e.channel || e;
Object.assign(DC.dc, setup)
}
post("to=bob&id="+DC.id, gotmsgs);
}
DC.send = function(data){
if (DC.dc && DC.dc.readyState=="open" && data) {
DC.dc.send(JSON.stringify(data));
}
}
})();