websocket.lua 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. -- Open database
  2. local db = sqlite3.open('r:\\websockLog.db')
  3. if db then
  4. db:busy_timeout(200);
  5. -- Create a table if it is not created already
  6. db:exec([[
  7. CREATE TABLE IF NOT EXISTS requests (
  8. id INTEGER PRIMARY KEY AUTOINCREMENT,
  9. timestamp NOT NULL,
  10. method NOT NULL,
  11. uri NOT NULL,
  12. addr
  13. );
  14. ]])
  15. end
  16. local function logDB(method)
  17. -- Add entry about this request
  18. local r;
  19. repeat
  20. r = db:exec([[INSERT INTO requests VALUES(NULL, datetime("now"), "]] .. method .. [[", "]] .. mg.request_info.uri .. [[", "]] .. mg.request_info.remote_port .. [[");]]);
  21. until r~=5;
  22. end
  23. -- Callback for "Websocket ready"
  24. function ready()
  25. logDB("WEBSOCKET READY")
  26. mg.write("text", "Websocket ready")
  27. end
  28. -- Callback for "Websocket received data"
  29. function data(bits, content)
  30. logDB(string.format("WEBSOCKET DATA (%x)", bits))
  31. mg.write("text", os.date())
  32. return true;
  33. end
  34. -- Callback for "Websocket is closing"
  35. function close()
  36. logDB("WEBSOCKET CLOSE")
  37. -- Close database
  38. db:close()
  39. end
  40. -- Websocket with coroutines
  41. logDB("WEBSOCKET PREPARE")
  42. coroutine.yield(true); -- first yield returns (true) or (false) to accept or reject the connection
  43. ready()
  44. repeat
  45. local cont, bits, content = coroutine.yield(true, 1.0)
  46. if bits and content then
  47. data(bits, content)
  48. end
  49. until not cont;
  50. mg.write("text", "end")
  51. close()