websocket.js 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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.callbacks = {connect: [], data: []};
  7. this.destination = null;
  8. this.reconnectInterval = options.reconnectInterval !== undefined
  9. ? options.reconnectInterval
  10. : 5;
  11. this.shouldAttemptReconnect = !!this.reconnectInterval;
  12. this.completed = false;
  13. this.established = false;
  14. this.progress = 0;
  15. this.reconnectTimeoutId = 0;
  16. };
  17. WSSource.prototype.connect = function(destination) {
  18. this.destination = destination;
  19. };
  20. WSSource.prototype.destroy = function() {
  21. clearTimeout(this.reconnectTimeoutId);
  22. this.shouldAttemptReconnect = false;
  23. this.socket.close();
  24. };
  25. WSSource.prototype.start = function() {
  26. this.shouldAttemptReconnect = !!this.reconnectInterval;
  27. this.progress = 0;
  28. this.established = false;
  29. this.socket = new WebSocket(this.url, this.options.protocols || null);
  30. this.socket.binaryType = 'arraybuffer';
  31. this.socket.onmessage = this.onMessage.bind(this);
  32. this.socket.onopen = this.onOpen.bind(this);
  33. this.socket.onerror = this.onClose.bind(this);
  34. this.socket.onclose = this.onClose.bind(this);
  35. };
  36. WSSource.prototype.resume = function(secondsHeadroom) {
  37. // Nothing to do here
  38. };
  39. WSSource.prototype.onOpen = function() {
  40. this.progress = 1;
  41. this.established = true;
  42. };
  43. WSSource.prototype.onClose = function() {
  44. if (this.shouldAttemptReconnect) {
  45. clearTimeout(this.reconnectTimeoutId);
  46. this.reconnectTimeoutId = setTimeout(function(){
  47. this.start();
  48. }.bind(this), this.reconnectInterval*1000);
  49. }
  50. };
  51. WSSource.prototype.onMessage = function(ev) {
  52. if (this.destination) {
  53. this.destination.write(ev.data);
  54. }
  55. };
  56. return WSSource;
  57. })();