You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

131 lines
3.7 KiB

4 years ago
  1. var Stream = require('stream').Stream,
  2. util = require('util'),
  3. driver = require('websocket-driver'),
  4. Headers = require('websocket-driver/lib/websocket/driver/headers'),
  5. API = require('./websocket/api'),
  6. EventTarget = require('./websocket/api/event_target'),
  7. Event = require('./websocket/api/event');
  8. var EventSource = function(request, response, options) {
  9. this.writable = true;
  10. options = options || {};
  11. this._stream = response.socket;
  12. this._ping = options.ping || this.DEFAULT_PING;
  13. this._retry = options.retry || this.DEFAULT_RETRY;
  14. var scheme = driver.isSecureRequest(request) ? 'https:' : 'http:';
  15. this.url = scheme + '//' + request.headers.host + request.url;
  16. this.lastEventId = request.headers['last-event-id'] || '';
  17. this.readyState = API.CONNECTING;
  18. var headers = new Headers(),
  19. self = this;
  20. if (options.headers) {
  21. for (var key in options.headers) headers.set(key, options.headers[key]);
  22. }
  23. if (!this._stream || !this._stream.writable) return;
  24. process.nextTick(function() { self._open() });
  25. this._stream.setTimeout(0);
  26. this._stream.setNoDelay(true);
  27. var handshake = 'HTTP/1.1 200 OK\r\n' +
  28. 'Content-Type: text/event-stream\r\n' +
  29. 'Cache-Control: no-cache, no-store\r\n' +
  30. 'Connection: close\r\n' +
  31. headers.toString() +
  32. '\r\n' +
  33. 'retry: ' + Math.floor(this._retry * 1000) + '\r\n\r\n';
  34. this._write(handshake);
  35. this._stream.on('drain', function() { self.emit('drain') });
  36. if (this._ping)
  37. this._pingTimer = setInterval(function() { self.ping() }, this._ping * 1000);
  38. ['error', 'end'].forEach(function(event) {
  39. self._stream.on(event, function() { self.close() });
  40. });
  41. };
  42. util.inherits(EventSource, Stream);
  43. EventSource.isEventSource = function(request) {
  44. if (request.method !== 'GET') return false;
  45. var accept = (request.headers.accept || '').split(/\s*,\s*/);
  46. return accept.indexOf('text/event-stream') >= 0;
  47. };
  48. var instance = {
  49. DEFAULT_PING: 10,
  50. DEFAULT_RETRY: 5,
  51. _write: function(chunk) {
  52. if (!this.writable) return false;
  53. try {
  54. return this._stream.write(chunk, 'utf8');
  55. } catch (e) {
  56. return false;
  57. }
  58. },
  59. _open: function() {
  60. if (this.readyState !== API.CONNECTING) return;
  61. this.readyState = API.OPEN;
  62. var event = new Event('open');
  63. event.initEvent('open', false, false);
  64. this.dispatchEvent(event);
  65. },
  66. write: function(message) {
  67. return this.send(message);
  68. },
  69. end: function(message) {
  70. if (message !== undefined) this.write(message);
  71. this.close();
  72. },
  73. send: function(message, options) {
  74. if (this.readyState > API.OPEN) return false;
  75. message = String(message).replace(/(\r\n|\r|\n)/g, '$1data: ');
  76. options = options || {};
  77. var frame = '';
  78. if (options.event) frame += 'event: ' + options.event + '\r\n';
  79. if (options.id) frame += 'id: ' + options.id + '\r\n';
  80. frame += 'data: ' + message + '\r\n\r\n';
  81. return this._write(frame);
  82. },
  83. ping: function() {
  84. return this._write(':\r\n\r\n');
  85. },
  86. close: function() {
  87. if (this.readyState > API.OPEN) return false;
  88. this.readyState = API.CLOSED;
  89. this.writable = false;
  90. if (this._pingTimer) clearInterval(this._pingTimer);
  91. if (this._stream) this._stream.end();
  92. var event = new Event('close');
  93. event.initEvent('close', false, false);
  94. this.dispatchEvent(event);
  95. return true;
  96. }
  97. };
  98. for (var method in instance) EventSource.prototype[method] = instance[method];
  99. for (var key in EventTarget) EventSource.prototype[key] = EventTarget[key];
  100. module.exports = EventSource;