1 | 'use strict';
|
---|
2 |
|
---|
3 | var inherits = require('inherits')
|
---|
4 | , EventEmitter = require('events').EventEmitter
|
---|
5 | , EventSourceDriver = require('eventsource')
|
---|
6 | ;
|
---|
7 |
|
---|
8 | var debug = function() {};
|
---|
9 | if (process.env.NODE_ENV !== 'production') {
|
---|
10 | debug = require('debug')('sockjs-client:receiver:eventsource');
|
---|
11 | }
|
---|
12 |
|
---|
13 | function EventSourceReceiver(url) {
|
---|
14 | debug(url);
|
---|
15 | EventEmitter.call(this);
|
---|
16 |
|
---|
17 | var self = this;
|
---|
18 | var es = this.es = new EventSourceDriver(url);
|
---|
19 | es.onmessage = function(e) {
|
---|
20 | debug('message', e.data);
|
---|
21 | self.emit('message', decodeURI(e.data));
|
---|
22 | };
|
---|
23 | es.onerror = function(e) {
|
---|
24 | debug('error', es.readyState, e);
|
---|
25 | // ES on reconnection has readyState = 0 or 1.
|
---|
26 | // on network error it's CLOSED = 2
|
---|
27 | var reason = (es.readyState !== 2 ? 'network' : 'permanent');
|
---|
28 | self._cleanup();
|
---|
29 | self._close(reason);
|
---|
30 | };
|
---|
31 | }
|
---|
32 |
|
---|
33 | inherits(EventSourceReceiver, EventEmitter);
|
---|
34 |
|
---|
35 | EventSourceReceiver.prototype.abort = function() {
|
---|
36 | debug('abort');
|
---|
37 | this._cleanup();
|
---|
38 | this._close('user');
|
---|
39 | };
|
---|
40 |
|
---|
41 | EventSourceReceiver.prototype._cleanup = function() {
|
---|
42 | debug('cleanup');
|
---|
43 | var es = this.es;
|
---|
44 | if (es) {
|
---|
45 | es.onmessage = es.onerror = null;
|
---|
46 | es.close();
|
---|
47 | this.es = null;
|
---|
48 | }
|
---|
49 | };
|
---|
50 |
|
---|
51 | EventSourceReceiver.prototype._close = function(reason) {
|
---|
52 | debug('close', reason);
|
---|
53 | var self = this;
|
---|
54 | // Safari and chrome < 15 crash if we close window before
|
---|
55 | // waiting for ES cleanup. See:
|
---|
56 | // https://code.google.com/p/chromium/issues/detail?id=89155
|
---|
57 | setTimeout(function() {
|
---|
58 | self.emit('close', null, reason);
|
---|
59 | self.removeAllListeners();
|
---|
60 | }, 200);
|
---|
61 | };
|
---|
62 |
|
---|
63 | module.exports = EventSourceReceiver;
|
---|