web-socket.html 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. clearInterval(this.reconnectTimer);
  19. this.reconnectTimer = undefined;
  20. var websocketUrl = (window.debug ? 'ws://' + window.location.hostname + ':3002' : 'wss://snapdrop.net') + '/binary';
  21. this.client = new BinaryClient(websocketUrl);
  22. this.client.on('stream', function(stream, meta) {
  23. // collect stream data
  24. var parts = [];
  25. stream.on('data', function(data) {
  26. //console.log('part received', meta, data);
  27. if (data.isSystemEvent) {
  28. if (meta) {
  29. data.from = meta.from;
  30. }
  31. this.fire('system-event', data);
  32. } else {
  33. parts.push(data);
  34. }
  35. }.bind(this));
  36. stream.on('end', function() {
  37. var blob = new Blob(parts, {
  38. type: meta.type
  39. });
  40. console.log('file received', blob, meta);
  41. this.fire('file-received', {
  42. blob: blob,
  43. name: meta.name,
  44. from: meta.from
  45. });
  46. }.bind(this));
  47. }.bind(this));
  48. this.client.on('open', function(e) {
  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. if (!this.reconnectTimer) {
  84. this.reconnectTimer = setInterval(this.init.bind(this), 3000);
  85. }
  86. }
  87. });
  88. </script>
  89. </dom-module>