websocket.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. JSMpeg.Source.WebSocket = (function(){ "use strict";
  2. var WSSource = function(url, options) {
  3. this.url = url;
  4. this.options = options;
  5. this.socket = null;
  6. this.streaming = true;
  7. this.callbacks = {connect: [], data: []};
  8. this.destination = null;
  9. this.reconnectInterval = options.reconnectInterval !== undefined
  10. ? options.reconnectInterval
  11. : 5;
  12. this.shouldAttemptReconnect = !!this.reconnectInterval;
  13. this.completed = false;
  14. this.established = false;
  15. this.progress = 0;
  16. this.reconnectTimeoutId = 0;
  17. this.onEstablishedCallback = options.onSourceEstablished;
  18. this.onCompletedCallback = options.onSourceCompleted; // Never used
  19. };
  20. WSSource.prototype.connect = function(destination) {
  21. this.destination = destination;
  22. };
  23. WSSource.prototype.destroy = function() {
  24. clearTimeout(this.reconnectTimeoutId);
  25. this.shouldAttemptReconnect = false;
  26. this.socket.close();
  27. };
  28. WSSource.prototype.start = function() {
  29. this.shouldAttemptReconnect = !!this.reconnectInterval;
  30. this.progress = 0;
  31. this.established = false;
  32. this.socket = new WebSocket(this.url, this.options.protocols || null);
  33. this.socket.binaryType = 'arraybuffer';
  34. this.socket.onmessage = this.onMessage.bind(this);
  35. this.socket.onopen = this.onOpen.bind(this);
  36. this.socket.onerror = this.onClose.bind(this);
  37. this.socket.onclose = this.onClose.bind(this);
  38. };
  39. WSSource.prototype.resume = function(secondsHeadroom) {
  40. // Nothing to do here
  41. };
  42. WSSource.prototype.onOpen = function() {
  43. this.progress = 1;
  44. };
  45. WSSource.prototype.onClose = function() {
  46. if (this.shouldAttemptReconnect) {
  47. clearTimeout(this.reconnectTimeoutId);
  48. this.reconnectTimeoutId = setTimeout(function(){
  49. this.start();
  50. }.bind(this), this.reconnectInterval*1000);
  51. }
  52. };
  53. WSSource.prototype.onMessage = function(ev) {
  54. var isFirstChunk = !this.established;
  55. this.established = true;
  56. if (isFirstChunk && this.onEstablishedCallback) {
  57. this.onEstablishedCallback(this);
  58. }
  59. if (this.destination) {
  60. this.destination.write(ev.data);
  61. }
  62. };
  63. return WSSource;
  64. })();