clients.lua

changeset 0
d363a6692a10
child 6
4e46ef3035ba
equal deleted inserted replaced
-1:000000000000 0:d363a6692a10
1 local socket = require "socket";
2 local server = require "net.server_select";
3 local http_server = require"net.http.server";
4 local log = require "util.logger".init("clients");
5
6 local response_head = table.concat({
7 "HTTP/1.1 200 OK";
8 "Max-Age: 0";
9 "Expires: 0";
10 "Cache-Control: no-cache, private";
11 "Pragma: no-cache";
12 "Content-Type: multipart/x-mixed-replace; boundary=--BoundaryString";
13 "Keep-Alive: timeout=5, max=99";
14 "Connection: Keep-Alive";
15 "Transfer-Encoding: chunked";
16 "";
17 "";
18 }, "\r\n");
19
20 local listener = { onconnect = function () end; onincoming = function () end; }
21
22 local last_chunk;
23
24 local clients = {};
25
26 -- Called when a HTTP stream client closes
27 function listener.ondisconnect(conn)
28 clients[conn] = nil;
29 if not next(clients) then
30 log("debug", "No more clients");
31 events.fire_event("no-clients");
32 end
33 end
34 listener.ondetach = listener.ondisconnect;
35
36 function handle_request(event, path)
37 local path = event.request.url.path;
38 if path ~= "/cam" then
39 return 404;
40 end
41
42 if not next(clients) then
43 log("debug", "Have clients now");
44 events.fire_event("have-clients");
45 end
46
47 local conn = event.response.conn;
48
49 conn:write(response_head);
50 clients[conn] = true;
51
52 if last_chunk then
53 conn:write(last_chunk);
54 end
55
56 conn:setlistener(listener);
57
58 return true;
59 end
60
61 events.add_handler("image-changed", function (event)
62 log("debug", "New image");
63 local chunk_data = table.concat({
64 "--BoundaryString",
65 "Content-Type: image/jpeg";
66 "Content-Length: "..#event.image;
67 "";
68 event.image;
69 }, "\r\n");
70 last_chunk = ("%x\r\n%s\r\n"):format(#chunk_data, chunk_data);
71
72 for client in pairs(clients) do
73 client:write(last_chunk);
74 end
75 end);
76
77 http_server.add_host("localhost");
78 http_server.set_default_host("localhost");
79 http_server.add_handler("GET localhost/*", handle_request);
80 http_server.listen_on(8006);

mercurial