summaryrefslogtreecommitdiff
path: root/main.lua
blob: 9673e28f2aea97de3ef01d077cbc5613213e1be7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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")

function onstream(server, stream)
    print("stream you.")
	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")
		stream:write_headers(response, false)
		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 not path:sub(#path-2,#path) == "/ws" or #path < 10 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-3)

	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 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())