--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/clients.lua Thu Dec 25 10:48:06 2014 +0000 @@ -0,0 +1,80 @@ +local socket = require "socket"; +local server = require "net.server_select"; +local http_server = require"net.http.server"; +local log = require "util.logger".init("clients"); + +local response_head = table.concat({ + "HTTP/1.1 200 OK"; + "Max-Age: 0"; + "Expires: 0"; + "Cache-Control: no-cache, private"; + "Pragma: no-cache"; + "Content-Type: multipart/x-mixed-replace; boundary=--BoundaryString"; + "Keep-Alive: timeout=5, max=99"; + "Connection: Keep-Alive"; + "Transfer-Encoding: chunked"; + ""; + ""; +}, "\r\n"); + +local listener = { onconnect = function () end; onincoming = function () end; } + +local last_chunk; + +local clients = {}; + +-- Called when a HTTP stream client closes +function listener.ondisconnect(conn) + clients[conn] = nil; + if not next(clients) then + log("debug", "No more clients"); + events.fire_event("no-clients"); + end +end +listener.ondetach = listener.ondisconnect; + +function handle_request(event, path) + local path = event.request.url.path; + if path ~= "/cam" then + return 404; + end + + if not next(clients) then + log("debug", "Have clients now"); + events.fire_event("have-clients"); + end + + local conn = event.response.conn; + + conn:write(response_head); + clients[conn] = true; + + if last_chunk then + conn:write(last_chunk); + end + + conn:setlistener(listener); + + return true; +end + +events.add_handler("image-changed", function (event) + log("debug", "New image"); + local chunk_data = table.concat({ + "--BoundaryString", + "Content-Type: image/jpeg"; + "Content-Length: "..#event.image; + ""; + event.image; + }, "\r\n"); + last_chunk = ("%x\r\n%s\r\n"):format(#chunk_data, chunk_data); + + for client in pairs(clients) do + client:write(last_chunk); + end +end); + +http_server.add_host("localhost"); +http_server.set_default_host("localhost"); +http_server.add_handler("GET localhost/*", handle_request); +http_server.listen_on(8006);