-
Notifications
You must be signed in to change notification settings - Fork 0
/
native-to-browser-test.html
326 lines (290 loc) · 10.6 KB
/
native-to-browser-test.html
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
<html>
<head>
<title>PeerConnection server test page</title>
</head>
<script>
var request = null;
var hangingGet = null;
var localName;
var server;
var myId = -1;
var otherPeers = {};
var messageCounter = 0;
var pc;
var pcConfig = {"iceServers": [{"url": "stun:stun.l.google.com:19302"}]};
var pcOptions = {
optional: [
{DtlsSrtpKeyAgreement: true}
]
}
var mediaConstraints = {'mandatory': {
'OfferToReceiveAudio': true,
'OfferToReceiveVideo': true }};
var remoteStream;
RTCPeerConnection = window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
RTCSessionDescription = window.mozRTCSessionDescription || window.RTCSessionDescription;
RTCIceCandidate = window.mozRTCIceCandidate || window.RTCIceCandidate;
getUserMedia = navigator.mozGetUserMedia || navigator.webkitGetUserMedia;
URL = window.webkitURL || window.URL;
function createPeerConnection(peer_id) {
try {
pc = new RTCPeerConnection(pcConfig, pcOptions);
pc.onicecandidate = function(event) {
if (event.candidate) {
var candidate = {
sdpMLineIndex: event.candidate.sdpMLineIndex,
sdpMid: event.candidate.sdpMid,
candidate: event.candidate.candidate
};
sendToPeer(peer_id, JSON.stringify(candidate));
} else {
console.log("End of candidates.");
}
};
pc.onconnecting = onSessionConnecting;
pc.onopen = onSessionOpened;
pc.onaddstream = onRemoteStreamAdded;
pc.onremovestream = onRemoteStreamRemoved;
console.log("Created RTCPeerConnnection with config: " + JSON.stringify(pcConfig));
}
catch (e) {
console.log("Failed to create PeerConnection with " + connectionId + ", exception: " + e.message);
}
}
function onRemoteStreamAdded(event) {
console.log("Remote stream added:", URL.createObjectURL(event.stream));
var remoteVideoElement = document.getElementById('remote-video');
remoteVideoElement.src = URL.createObjectURL(event.stream);
remoteVideoElement.play();
}
function sld_success_cb() {
}
function sld_failure_cb() {
console.log("setLocalDescription failed");
}
function aic_success_cb() {
}
function aic_failure_cb() {
console.log("addIceCandidate failed");
}
function handlePeerMessage(peer_id, data) {
++messageCounter;
var str = "Message from '" + otherPeers[peer_id] + ":" + data;
trace(str);
var dataJson = JSON.parse(data);
console.log("received ", dataJson);
if (data.search("offer") != -1) {
createPeerConnection(peer_id);
pc.setRemoteDescription(new RTCSessionDescription(dataJson), onRemoteSdpSucces, onRemoteSdpError);
pc.createAnswer(function(sessionDescription) {
console.log("Create answer:", sessionDescription);
pc.setLocalDescription(sessionDescription,sld_success_cb,sld_failure_cb);
var data = JSON.stringify(sessionDescription);
sendToPeer(peer_id, data);
}, function(error) { // error
console.log("Create answer error:", error);
}, mediaConstraints); // type error ); //}, null
}
else {
console.log("Adding ICE candiate ", dataJson);
var candidate = new RTCIceCandidate({sdpMLineIndex: dataJson.sdpMLineIndex, candidate: dataJson.candidate});
pc.addIceCandidate(candidate, aic_success_cb, aic_failure_cb);
}
}
function trace(txt) {
var elem = document.getElementById("debug");
elem.innerHTML += txt + "<br>";
}
function handleServerNotification(data) {
trace("Server notification: " + data);
var parsed = data.split(',');
if (parseInt(parsed[2]) != 0)
otherPeers[parseInt(parsed[1])] = parsed[0];
}
function parseIntHeader(r, name) {
var val = r.getResponseHeader(name);
return val != null && val.length ? parseInt(val) : -1;
}
function hangingGetCallback() {
try {
if (hangingGet.readyState != 4)
return;
if (hangingGet.status != 200) {
trace("server error: " + hangingGet.statusText);
disconnect();
} else {
var peer_id = parseIntHeader(hangingGet, "Pragma");
console.log("Message from:", peer_id, ':', hangingGet.responseText);
if (peer_id == myId) {
handleServerNotification(hangingGet.responseText);
} else {
handlePeerMessage(peer_id, hangingGet.responseText);
}
}
if (hangingGet) {
hangingGet.abort();
hangingGet = null;
}
if (myId != -1)
window.setTimeout(startHangingGet, 0);
} catch (e) {
trace("Hanging get error: " + e.description);
}
}
function startHangingGet() {
try {
hangingGet = new XMLHttpRequest();
hangingGet.onreadystatechange = hangingGetCallback;
hangingGet.ontimeout = onHangingGetTimeout;
hangingGet.open("GET", server + "/wait?peer_id=" + myId, true);
hangingGet.send();
} catch (e) {
trace("error" + e.description);
}
}
function onHangingGetTimeout() {
trace("hanging get timeout. issuing again.");
hangingGet.abort();
hangingGet = null;
if (myId != -1)
window.setTimeout(startHangingGet, 0);
}
function signInCallback() {
try {
if (request.readyState == 4) {
if (request.status == 200) {
var peers = request.responseText.split("\n");
myId = parseInt(peers[0].split(',')[1]);
trace("My id: " + myId);
for (var i = 1; i < peers.length; ++i) {
if (peers[i].length > 0) {
trace("Peer " + i + ": " + peers[i]);
var parsed = peers[i].split(',');
otherPeers[parseInt(parsed[1])] = parsed[0];
}
}
startHangingGet();
request = null;
}
}
} catch (e) {
trace("error: " + e.description);
}
}
function signIn() {
try {
request = new XMLHttpRequest();
request.onreadystatechange = signInCallback;
request.open("GET", server + "/sign_in?" + localName, true);
request.send();
} catch (e) {
trace("error: " + e.description);
}
}
function dummy() {
}
function sendToPeer(peer_id, data) {
try {
console.log(peer_id," Send ", data);
if (myId == -1) {
alert("Not connected");
return;
}
if (peer_id == myId) {
alert("Can't send a message to oneself :)");
return;
}
var r = new XMLHttpRequest();
r.onreadystatechange = dummy
r.open("POST", server + "/message?peer_id=" + myId + "&to=" + peer_id, true);
r.setRequestHeader("Content-Type", "text/plain");
r.send(data);
} catch (e) {
trace("send to peer error: " + e.description);
}
}
function connect() {
localName = document.getElementById("local").value.toLowerCase();
server = document.getElementById("server").value.toLowerCase();
if (localName.length == 0) {
alert("I need a name please.");
document.getElementById("local").focus();
} else {
document.getElementById("connect").disabled = true;
document.getElementById("disconnect").disabled = false;
signIn();
}
}
function disconnect() {
if (request) {
request.abort();
request = null;
}
if (hangingGet) {
hangingGet.abort();
hangingGet = null;
}
if (myId != -1) {
request = new XMLHttpRequest();
request.open("GET", server + "/sign_out?peer_id=" + myId, false);
request.send();
request = null;
myId = -1;
}
document.getElementById("connect").disabled = false;
document.getElementById("disconnect").disabled = true;
}
window.onbeforeunload = disconnect;
function send() {
var text = document.getElementById("message").value;
var peer_id = parseInt(document.getElementById("peer_id").value);
if (!text.length || peer_id == 0) {
alert("No text supplied or invalid peer id");
} else {
sendToPeer(peer_id, text);
}
}
function toggleMe(obj) {
var id = obj.id.replace("toggle", "msg");
var t = document.getElementById(id);
if (obj.innerText == "+") {
obj.innerText = "-";
t.style.display = "block";
} else {
obj.innerText = "+";
t.style.display = "none";
}
}
function onSessionConnecting(message) {
console.log("Session connecting.");
}
function onSessionOpened(message) {
console.log("Session opened.");
}
function onRemoteStreamRemoved(event) {
console.log("Remote stream removed.");
}
function onRemoteSdpError(event) {
console.error('onRemoteSdpError', event.name, event.message);
}
function onRemoteSdpSucces() {
console.log('onRemoteSdpSucces');
}
</script>
<body>
<div id="container">
<div id="remote">
<video id="remote-video" width="50%" height="50%"></video>
</div>
</div>
Server: <input type="text" id="server" value="http://135.222.138.136:8888" /><br>
Your name: <input type="text" id="local" value="myclient"/>
<button id="connect" onclick="connect();">Connect</button>
<button disabled="true" id="disconnect" onclick="disconnect();">Disconnect</button>
<br>
<button onclick="document.getElementById('debug').innerHTML='';">Clear log</button>
<pre id="debug"></pre>
<br>
<hr>
</body>
</html>