websocket.lua 847 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. repeat
  25. local cont, bits, content = coroutine.yield(true, 1.0)
  26. mg.write("text", os.date());
  27. if bits and content then
  28. data(bits, content)
  29. end
  30. until not cont;
  31. mg.write("text", "end")
  32. close()