Socket.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. var defaults = require('./defaults');
  2. var Emitter = require('./Emitter');
  3. exports = Emitter.extend({
  4. initialize: function Socket(url) {
  5. var options =
  6. arguments.length > 1 && arguments[1] !== undefined
  7. ? arguments[1]
  8. : {};
  9. this.callSuper(Emitter, 'initialize');
  10. defaults(options, defOpts);
  11. this._options = options;
  12. this._url = url;
  13. this.connect();
  14. },
  15. send: function(message) {
  16. this._ws.send(message);
  17. },
  18. close: function(code, reason) {
  19. this._ws.close(code || 1e3, reason);
  20. },
  21. connect: function() {
  22. var _this = this;
  23. var options = this._options;
  24. var ws = new WebSocket(this._url, options.protocols);
  25. ws.onmessage = function(e) {
  26. return _this.emit('message', e);
  27. };
  28. ws.onopen = function(e) {
  29. return _this.emit('open', e);
  30. };
  31. ws.onclose = function(e) {
  32. var code = e.code;
  33. if (
  34. code !== 1e3 &&
  35. code !== 1001 &&
  36. code !== 1005 &&
  37. options.reconnect
  38. ) {
  39. _this.connect();
  40. }
  41. _this.emit('close', e);
  42. };
  43. ws.onerror = function(e) {
  44. if (e && e.code === 'ECONNREFUSED' && options.reconnect) {
  45. _this.connect();
  46. } else {
  47. _this.emit('error', e);
  48. }
  49. };
  50. this._ws = ws;
  51. }
  52. });
  53. var defOpts = {
  54. protocols: [],
  55. reconnect: true
  56. };
  57. module.exports = exports;