18.12.2018, 12:58
.lp can already work as WebSocket server. Here's a short example:
jQuery is required for localbus, but only $.ajax, $.param and $.each functions are used. I suppose you can provide your own compatibility layer if using any other JS library.
Code:
<?
local json = require('json')
local ws, err = require('ngx.ws'):new({ timeout = 10 * 1000 })
-- websocket init error
if not ws then
write('websocket init failed: ', tostring(err))
return
end
request.raw = true
local lb = require('localbus')
local function lbthread(ws)
local client = lb.new()
local run = true
-- telegram event
local function groupcallback(event)
event.tsec, event.tusec = os.microtime()
local data = json.encode(event)
if not ws:send_text(data) then
run = false
end
end
-- set callbacks
client:sethandler('groupwrite', groupcallback)
client:sethandler('groupresponse', groupcallback)
while run do
client:step()
end
end
local function datacallback(data)
-- ignore ping messages
if data == 'ping' then
return
end
data = json.pdecode(data)
end
local co = ngx.thread.spawn(lbthread, ws)
repeat
local data, typ, err = ws:recv_frame()
if typ == 'text' then
datacallback(data)
end
until ws.fatal or typ == 'close' or ngx.worker.exiting()
ngx.thread.kill(co)
if not ws.fatal then
ws:send_close()
end
jQuery is required for localbus, but only $.ajax, $.param and $.each functions are used. I suppose you can provide your own compatibility layer if using any other JS library.