|
1 local stream_methods = {}; |
|
2 local stream_mt = { __index = stream_methods }; |
|
3 |
|
4 local response_head = table.concat({ |
|
5 "HTTP/1.1 200 OK"; |
|
6 "Content-Type: text/event-stream"; |
|
7 ""; |
|
8 ""; |
|
9 }, "\r\n"); |
|
10 |
|
11 function stream_methods:add_watcher(conn) |
|
12 conn:write(response_head); |
|
13 self.watchers[conn] = true; |
|
14 end |
|
15 |
|
16 function stream_methods:remove_watcher(conn) |
|
17 self.watchers[conn] = nil; |
|
18 end |
|
19 |
|
20 function stream_methods:push(data) |
|
21 data = "data: "..data:gsub("\n", "\ndata: \n").."\n\n"; |
|
22 for conn in pairs(self.watchers) do |
|
23 conn:write(data); |
|
24 end |
|
25 end |
|
26 |
|
27 function stream_methods:is_unwatched() |
|
28 return next(self.watchers) == nil; |
|
29 end |
|
30 |
|
31 local function new() |
|
32 return setmetatable({ watchers = {} }, stream_mt); |
|
33 end |
|
34 |
|
35 return { new = new }; |