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