| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 | 
function trace(text)    local f = io.open("websocket2.trace", "a")    f:write(os.date() .. " - " .. text .. "\n")    f:close()endfunction iswebsocket()  return mg.lua_type == "websocket"endtrace("called with Lua type " .. tostring(mg.lua_type))if not iswebsocket() then  trace("no websocket")  mg.write("HTTP/1.0 403 Forbidden\r\n")  mg.write("Connection: close\r\n")  mg.write("\r\n")  mg.write("forbidden")  returnend-- Serialize table to stringfunction ser(val)  local t  if type(val) == "table" then    for k,v in pairs(val) do      if t then        t = t .. ", " .. ser(k) .. "=" .. ser(v)      else        t = "{" .. ser(k) .. "=" .. ser(v)      end    end    t = t .. "}"  else    t = tostring(val)  end  return tend-- table of all active connectionallConnections = {}-- function to get a client identification stringfunction who(tab)  local ri = allConnections[tab.client].request_info  return ri.remote_addr .. ":" .. ri.remote_portend-- Callback to accept or reject a connectionfunction open(tab)  allConnections[tab.client] = tab  trace("open[" .. who(tab) .. "]: " .. ser(tab))  return true -- return true to accept the connectionend-- Callback for "Websocket ready"function ready(tab)  trace("ready[" .. who(tab) .. "]: " .. ser(tab))  mg.write(tab.client, "text", "Websocket ready")  mg.write(tab.client, 1, "-->h 180");  mg.write(tab.client, "-->m 180");  senddata()  mg.set_interval(timer, 1)  return true -- return true to keep the connection openend-- Callback for "Websocket received data"function data(tab)    trace("data[" .. who(tab) .. "]: " .. ser(tab))    senddata()    return true -- return true to keep the connection openend-- Callback for "Websocket is closing"function close(tab)    trace("close[" .. who(tab) .. "]: " .. ser(tab))    mg.write("text", "end")    allConnections[tab.client] = nilendfunction senddata()    local date = os.date('*t');    local hand = (date.hour%12)*60+date.min;    mg.write("text", string.format("%u:%02u:%02u", date.hour, date.min, date.sec));    if (hand ~= lasthand) then        mg.write(1, string.format("-->h %f", hand*360/(12*60)));        mg.write(   string.format("-->m %f", date.min*360/60));        lasthand = hand;    end    if bits and content then        data(bits, content)    endendfunction timer()    trace("timer")    senddata()    return true -- return true to keep an interval timer runningend
 |