websocket.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. This file is part of ethereum.js.
  3. ethereum.js is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Lesser General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. ethereum.js is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public License
  12. along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. /** @file websocket.js
  15. * @authors:
  16. * Jeffrey Wilcke <jeff@ethdev.com>
  17. * Marek Kotewicz <marek@ethdev.com>
  18. * Marian Oancea <marian@ethdev.com>
  19. * @date 2014
  20. */
  21. // TODO: work out which of the following two lines it is supposed to be...
  22. //if (process.env.NODE_ENV !== 'build') {
  23. if ("build" !== "build") {/*
  24. var WebSocket = require('ws'); // jshint ignore:line
  25. */}
  26. var WebSocketProvider = function(host) {
  27. // onmessage handlers
  28. this.handlers = [];
  29. // queue will be filled with messages if send is invoked before the ws is ready
  30. this.queued = [];
  31. this.ready = false;
  32. this.ws = new WebSocket(host);
  33. var self = this;
  34. this.ws.onmessage = function(event) {
  35. for(var i = 0; i < self.handlers.length; i++) {
  36. self.handlers[i].call(self, JSON.parse(event.data), event);
  37. }
  38. };
  39. this.ws.onopen = function() {
  40. self.ready = true;
  41. for(var i = 0; i < self.queued.length; i++) {
  42. // Resend
  43. self.send(self.queued[i]);
  44. }
  45. };
  46. };
  47. WebSocketProvider.prototype.send = function(payload) {
  48. if(this.ready) {
  49. var data = JSON.stringify(payload);
  50. this.ws.send(data);
  51. } else {
  52. this.queued.push(payload);
  53. }
  54. };
  55. WebSocketProvider.prototype.onMessage = function(handler) {
  56. this.handlers.push(handler);
  57. };
  58. WebSocketProvider.prototype.unload = function() {
  59. this.ws.close();
  60. };
  61. Object.defineProperty(WebSocketProvider.prototype, "onmessage", {
  62. set: function(provider) { this.onMessage(provider); }
  63. });
  64. module.exports = WebSocketProvider;