websocket.lua 1.4 KB

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