-
Notifications
You must be signed in to change notification settings - Fork 41
/
trace-ws.js
55 lines (51 loc) · 1.33 KB
/
trace-ws.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
var PROTOCOL_VERSION = '2.0';
module.exports = function(wsURL) {
var buffer;
var connection;
var trace = function() {
//console.log.apply(console, arguments);
// TODO: drop getStats when not connected?
var args = Array.prototype.slice.call(arguments);
args.push(new Date().getTime());
if (args[1] instanceof RTCPeerConnection) {
args[1] = args[1].__rtcStatsId;
}
if (connection.readyState === WebSocket.OPEN) {
connection.send(JSON.stringify(args));
} else if (connection.readyState >= WebSocket.CLOSING) {
// no-op. Possibly log?
} else if (args[0] !== 'getstats') {
buffer.push(args);
}
};
trace.close = function() {
connection.close();
};
trace.connect = function() {
buffer = [];
if (connection) {
connection.close();
}
connection = new WebSocket(wsURL + window.location.pathname, PROTOCOL_VERSION);
connection.onerror = function(e) {
console.log('WS ERROR', e);
};
/*
connection.onclose = function() {
// reconnect?
};
*/
connection.onopen = function() {
while (buffer.length) {
connection.send(JSON.stringify(buffer.shift()));
}
};
/*
connection.onmessage = function(msg) {
// no messages from the server defined yet.
};
*/
};
trace.connect();
return trace;
};