web-socket.html 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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.location.protocol === 'https:' ? 'wss://' : 'ws://') + document.location.hostname + ':9001';
  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. console.log(e);
  49. this.client.send({}, {
  50. handshake: this.me
  51. });
  52. }.bind(this));
  53. this.client.on('error', function(e) {
  54. console.log(e);
  55. });
  56. this.client.on('close', function(e) {
  57. console.log(e);
  58. //try to reconnect after 3s
  59. this.async(this.init, 3000);
  60. }.bind(this));
  61. },
  62. _sendFile: function(toPeer, file) {
  63. console.log('send file!', 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. });
  81. </script>
  82. </dom-module>