web-socket.html 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <link rel="import" href="binaryjs.html">
  2. <dom-module id="web-socket">
  3. <template>
  4. <style>
  5. :host {
  6. display: block;
  7. }
  8. </style>
  9. </template>
  10. <script>
  11. 'use strict';
  12. Polymer({
  13. is: 'web-socket',
  14. attached: function() {
  15. this.init();
  16. },
  17. init: function() {
  18. var websocketUrl = (window.debug ? 'ws://' + window.location.hostname + ':3002' : 'wss://snapdrop.net') + '/binary';
  19. this.client = new BinaryClient(websocketUrl);
  20. this.client.on('stream', function(stream, meta) {
  21. // collect stream data
  22. var parts = [];
  23. stream.on('data', function(data) {
  24. //console.log('part received', meta, data);
  25. if (data.isSystemEvent) {
  26. if (meta) {
  27. data.from = meta.from;
  28. }
  29. this.fire('system-event', data);
  30. } else {
  31. parts.push(data);
  32. }
  33. }.bind(this));
  34. // when finished, set it as the background image
  35. stream.on('end', function() {
  36. var blob = new Blob(parts, {
  37. type: meta.type
  38. });
  39. console.log('file received', blob, meta);
  40. this.fire('file-received', {
  41. blob: blob,
  42. name: meta.name,
  43. from: meta.from
  44. });
  45. }.bind(this));
  46. }.bind(this));
  47. this.client.on('open', function(e) {
  48. this.cancelAsync(this.reconnectTimer);
  49. console.log(e);
  50. this.client.send({}, {
  51. serverMsg: 'rtc-support',
  52. rtc: window.webRTCSupported
  53. });
  54. }.bind(this));
  55. this.client.on('error', function(e) {
  56. this._reconnect(e);
  57. }.bind(this));
  58. this.client.on('close', function(e) {
  59. this._reconnect(e);
  60. }.bind(this));
  61. },
  62. _sendFile: function(toPeer, file) {
  63. console.log('send file via WebSocket', file);
  64. this.client.send(file.file, {
  65. name: file.file.name,
  66. type: file.file.type,
  67. toPeer: toPeer
  68. });
  69. },
  70. connectToPeer: function(peer, callback) {
  71. callback();
  72. },
  73. _sendSystemEvent: function(toPeer, event) {
  74. console.log('system event', toPeer, event);
  75. event.isSystemEvent = true;
  76. this.client.send(event, {
  77. toPeer: toPeer
  78. });
  79. },
  80. _reconnect: function(e) {
  81. console.log('disconnected', e);
  82. //try to reconnect after 3s
  83. this.reconnectTimer = this.async(this.init, 3000);
  84. }
  85. });
  86. </script>
  87. </dom-module>