sseclient.js
1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
var util = require('util'),
events = require('events');
module.exports = SSEClient;
function SSEClient(req, res) {
this.req = req;
this.res = res;
var self = this;
res.on('close', function() {
self.emit('close');
});
}
util.inherits(SSEClient, events.EventEmitter);
SSEClient.prototype.initialize = function() {
this.req.socket.setNoDelay(true);
this.res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache, no-transform',
'Connection': 'keep-alive'
});
this.res.write(':ok\n\n');
};
SSEClient.prototype.send = function(event, data, id) {
if (arguments.length === 0) return;
var senderObject = {
event : event || undefined,
data : data || undefined,
id : id || undefined,
retry : undefined
};
if (typeof event == 'object') {
senderObject.event = event.event || undefined,
senderObject.data = event.data || undefined,
senderObject.id = event.id || undefined,
senderObject.retry = event.retry || undefined
}
if (typeof event != 'object' && arguments.length === 1) {
senderObject.event = undefined;
senderObject.data = event;
}
if (senderObject.event) this.res.write('event: ' + senderObject.event + '\n');
if (senderObject.retry) this.res.write('retry: ' + senderObject.retry + '\n');
if (senderObject.id) this.res.write('id: ' + senderObject.id + '\n');
senderObject.data = senderObject.data.replace(/(\r\n|\r|\n)/g, '\n');
var dataLines = senderObject.data.split(/\n/);
for (var i = 0, l = dataLines.length; i < l; ++i) {
var line = dataLines[i];
if ((i+1) === l) this.res.write('data: ' + line + '\n\n');
else this.res.write('data: ' + line + '\n');
}
}
SSEClient.prototype.close = function() {
this.res.end();
}