websocket.lua 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. function trace(text)
  2. local f = io.open("R:\\websocket.trace", "a")
  3. f:write(os.date() .. " - " .. text .. "\n")
  4. f:close()
  5. end
  6. function iswebsocket()
  7. return mg.lua_type == "websocket"
  8. --return pcall(function()
  9. -- if (string.upper(mg.request_info.http_headers.Upgrade)~="WEBSOCKET") then error("") end
  10. --end)
  11. end
  12. trace("called with Lua type " .. tostring(mg.lua_type))
  13. if not iswebsocket() then
  14. trace("no websocket")
  15. mg.write("HTTP/1.0 403 Forbidden\r\n")
  16. mg.write("Connection: close\r\n")
  17. mg.write("\r\n")
  18. mg.write("forbidden")
  19. return
  20. end
  21. -- Callback to reject a connection
  22. function open()
  23. trace("open")
  24. return true
  25. end
  26. -- Callback for "Websocket ready"
  27. function ready()
  28. trace("ready")
  29. mg.write("text", "Websocket ready")
  30. senddata()
  31. return true
  32. end
  33. -- Callback for "Websocket received data"
  34. function data(bits, content)
  35. trace("data(" .. bits .. "): " .. content)
  36. senddata()
  37. return true
  38. end
  39. -- Callback for "Websocket is closing"
  40. function close()
  41. trace("close")
  42. mg.write("text", "end")
  43. end
  44. function senddata()
  45. trace("senddata")
  46. local date = os.date('*t');
  47. local hand = (date.hour%12)*60+date.min;
  48. mg.write("text", string.format("%u:%02u:%02u", date.hour, date.min, date.sec));
  49. if (hand ~= lasthand) then
  50. mg.write("text", string.format("-->h %u", hand*360/(12*60)));
  51. mg.write("text", string.format("-->m %u", date.min*360/60));
  52. lasthand = hand;
  53. end
  54. if bits and content then
  55. data(bits, content)
  56. end
  57. end