websocket.lua 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. -- table of all active connection
  39. allConnections = {}
  40. -- function to get a client identification string
  41. function who(tab)
  42. local ri = allConnections[tab.client]
  43. return ri.remote_addr .. ":" .. ri.remote_port
  44. end
  45. -- Callback to reject a connection
  46. function open(tab)
  47. allConnections[tab.client] = tab.request_info
  48. trace("open[" .. who(tab) .. "]: " .. ser(tab))
  49. return true
  50. end
  51. -- Callback for "Websocket ready"
  52. function ready(tab)
  53. trace("ready[" .. who(tab) .. "]: " .. ser(tab))
  54. mg.write("text", "Websocket ready")
  55. senddata()
  56. return true
  57. end
  58. -- Callback for "Websocket received data"
  59. function data(tab)
  60. trace("data[" .. who(tab) .. "]: " .. ser(tab))
  61. senddata()
  62. return true
  63. end
  64. -- Callback for "Websocket is closing"
  65. function close(tab)
  66. trace("close[" .. who(tab) .. "]: " .. ser(tab))
  67. mg.write("text", "end")
  68. allConnections[tab.client] = nil
  69. end
  70. function senddata()
  71. trace("senddata")
  72. local date = os.date('*t');
  73. local hand = (date.hour%12)*60+date.min;
  74. mg.write("text", string.format("%u:%02u:%02u", date.hour, date.min, date.sec));
  75. if (hand ~= lasthand) then
  76. mg.write("text", string.format("-->h %u", hand*360/(12*60)));
  77. mg.write("text", string.format("-->m %u", date.min*360/60));
  78. lasthand = hand;
  79. end
  80. if bits and content then
  81. data(bits, content)
  82. end
  83. end