forked from phoboslab/jsmpeg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocket.js
83 lines (64 loc) · 1.98 KB
/
websocket.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
JSMpeg.Source.WebSocket = (function(){ "use strict";
var WSSource = function(url, options) {
this.url = url;
this.options = options;
this.socket = null;
this.streaming = true;
this.callbacks = {connect: [], data: []};
this.destination = null;
this.reconnectInterval = options.reconnectInterval !== undefined
? options.reconnectInterval
: 5;
this.shouldAttemptReconnect = !!this.reconnectInterval;
this.completed = false;
this.established = false;
this.progress = 0;
this.reconnectTimeoutId = 0;
this.onEstablishedCallback = options.onSourceEstablished;
this.onCompletedCallback = options.onSourceCompleted; // Never used
};
WSSource.prototype.connect = function(destination) {
this.destination = destination;
};
WSSource.prototype.destroy = function() {
clearTimeout(this.reconnectTimeoutId);
this.shouldAttemptReconnect = false;
this.socket.close();
};
WSSource.prototype.start = function() {
this.shouldAttemptReconnect = !!this.reconnectInterval;
this.progress = 0;
this.established = false;
this.socket = new WebSocket(this.url, this.options.protocols || null);
this.socket.binaryType = 'arraybuffer';
this.socket.onmessage = this.onMessage.bind(this);
this.socket.onopen = this.onOpen.bind(this);
this.socket.onerror = this.onClose.bind(this);
this.socket.onclose = this.onClose.bind(this);
};
WSSource.prototype.resume = function(secondsHeadroom) {
// Nothing to do here
};
WSSource.prototype.onOpen = function() {
this.progress = 1;
};
WSSource.prototype.onClose = function() {
if (this.shouldAttemptReconnect) {
clearTimeout(this.reconnectTimeoutId);
this.reconnectTimeoutId = setTimeout(function(){
this.start();
}.bind(this), this.reconnectInterval*1000);
}
};
WSSource.prototype.onMessage = function(ev) {
var isFirstChunk = !this.established;
this.established = true;
if (isFirstChunk && this.onEstablishedCallback) {
this.onEstablishedCallback(this);
}
if (this.destination) {
this.destination.write(ev.data);
}
};
return WSSource;
})();