print("it is already far, far too late.") local cqueues = require("cqueues") local cq = cqueues.new() local httpserver = require("http.server") local websocket = require("http.websocket") local headers = require "http.headers" local logic = require("server_logic") local function reject(stream, code, reason) local response = headers.new() response:append(":status", tostring(code)) stream:write_headers(response, false) stream:write_chunk(reason, true) end local function onstream(server, stream) print("stream you.") local head = stream:get_headers() local path = head:get(":path") local room = path:match '^/room/(%w+)/ws$' if not room then reject(stream, 404, "path not found: "..path) return end local ws = websocket.new_from_stream(stream, head) if not ws then reject(stream, 400, "bad request: not a websocket handshake") return end ws:accept() logic.onsocket(ws,room) local ws_open = true local 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 or not ws_open then close() return end logic.onmessage(ws, data) end end local sv = httpserver.listen { host = "127.0.0.1", port = "61111", onstream = onstream, } sv:listen() cq:wrap(function() assert(sv:loop()) end) assert(cq:loop())