diff options
Diffstat (limited to 'main.lua')
-rw-r--r-- | main.lua | 48 |
1 files changed, 45 insertions, 3 deletions
@@ -7,9 +7,12 @@ local httpserver = require("http.server") local websocket = require("http.websocket") local headers = require "http.headers" +local logic = require("server_logic") + function onstream(server, stream) print("stream you.") - local ws = websocket.new_from_stream(stream, stream:get_headers()) + local head = stream:get_headers() + local ws = websocket.new_from_stream(stream, head) if not ws then local response = headers.new() response:append(":status", "400") @@ -17,11 +20,50 @@ function onstream(server, stream) stream:write_chunk("bad request: not a websocket handshake", true) return end + + local path = head:get(":path") + if not path:sub(1,6) == "/room/" or #path < 7 then + local response = headers.new() + response:append(":status", "404") + stream:write_headers(response, false) + stream:write_chunk("please access /room/(roomname).", true) + return + end + local room = path:sub(7,#path) + ws:accept() + logic.onsocket(ws,room) + + local ws_open = true + function close() + logic.onclose(ws) + if ws_open then ws:close() end + ws_open = false + + end + + cq:wrap(function() + while true do + logic.ping(ws) + cqueues.sleep(logic.ping_interval) + if not ws_open then break end + if os.time() - logic.last_ping(ws) >= 18 then + close() + return + end + end + end) + while true do + if not ws_open then + return + end local data = ws:receive() - if not data then return end - ws:send(data) + if not data or not ws_open then + close() + return + end + logic.onmessage(ws, data) end end |