websocket.lua 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. function iswebsocket()
  2. return pcall(function()
  3. if (string.upper(mg.request_info.http_headers.Upgrade)~="WEBSOCKET") then error("") end
  4. end)
  5. end
  6. if not iswebsocket() then
  7. mg.write("HTTP/1.0 403 Forbidden\r\n")
  8. mg.write("Connection: close\r\n")
  9. mg.write("\r\n")
  10. return
  11. end
  12. -- Callback for "Websocket ready"
  13. function ready()
  14. mg.write("text", "Websocket ready")
  15. end
  16. -- Callback for "Websocket received data"
  17. function data(bits, content)
  18. end
  19. -- Callback for "Websocket is closing"
  20. function close()
  21. end
  22. coroutine.yield(true); -- first yield returns (true) or (false) to accept or reject the connection
  23. ready()
  24. local lasthand = ""
  25. repeat
  26. local cont, bits, content = coroutine.yield(true, 1.0)
  27. local date = os.date('*t');
  28. local hand = (date.hour%12)*60+date.min;
  29. mg.write("text", string.format("%u:%02u:%02u", date.hour, date.min, date.sec));
  30. if (hand ~= lasthand) then
  31. mg.write("text", string.format("-->h %u", hand*360/(12*60)));
  32. mg.write("text", string.format("-->m %u", date.min*360/60));
  33. lasthand = hand;
  34. end
  35. if bits and content then
  36. data(bits, content)
  37. end
  38. until not cont;
  39. mg.write("text", "end")
  40. close()