This forum uses cookies
This forum makes use of cookies to store your login information if you are registered, and your last visit if you are not. Cookies are small text documents stored on your computer; the cookies set by this forum can only be used on this website and pose no security risk. Cookies on this forum also track the specific topics you have read and when you last read them. Please confirm that you accept these cookies being set.

Socket.io server on .lp file
#4
.lp can already work as WebSocket server. Here's a short example:
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.
Reply


Messages In This Thread
Socket.io server on .lp file - by buuuudzik - 18.12.2018, 10:13
RE: Socket.io server on .lp file - by admin - 18.12.2018, 10:54
RE: Socket.io server on .lp file - by admin - 18.12.2018, 12:58
RE: Socket.io server on .lp file - by admin - 18.12.2018, 15:38
RE: Socket.io server on .lp file - by admin - 18.12.2018, 16:57
RE: Socket.io server on .lp file - by admin - 18.12.2018, 19:30

Forum Jump: