websocket.lua 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. -- Serialize table to string
  22. function ser(val)
  23. local t
  24. if type(val) == "table" then
  25. for k,v in pairs(val) do
  26. if t then
  27. t = t .. ", " .. ser(k) .. "=" .. ser(v)
  28. else
  29. t = "{" .. ser(k) .. "=" .. ser(v)
  30. end
  31. end
  32. t = t .. "}"
  33. else
  34. t = tostring(val)
  35. end
  36. return t
  37. end
  38. -- Callback to reject a connection
  39. function open()
  40. trace("open")
  41. return true
  42. end
  43. -- Callback for "Websocket ready"
  44. function ready(tab)
  45. trace("ready: " .. ser(tab))
  46. mg.write("text", "Websocket ready")
  47. senddata()
  48. return true
  49. end
  50. -- Callback for "Websocket received data"
  51. function data(tab)
  52. trace("data: " .. ser(tab))
  53. senddata()
  54. return true
  55. end
  56. -- Callback for "Websocket is closing"
  57. function close(tab)
  58. trace("close: " .. ser(tab))
  59. mg.write("text", "end")
  60. end
  61. function senddata()
  62. trace("senddata")
  63. local date = os.date('*t');
  64. local hand = (date.hour%12)*60+date.min;
  65. mg.write("text", string.format("%u:%02u:%02u", date.hour, date.min, date.sec));
  66. if (hand ~= lasthand) then
  67. mg.write("text", string.format("-->h %u", hand*360/(12*60)));
  68. mg.write("text", string.format("-->m %u", date.min*360/60));
  69. lasthand = hand;
  70. end
  71. if bits and content then
  72. data(bits, content)
  73. end
  74. end