websocket.lua 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. local websocket = require "http.websocket"
  2. local copas = require "copas"
  3. local cjson = require "cjson"
  4. WebSocketClient = {}
  5. WebSocketClient.__index = WebSocketClient
  6. function WebSocketClient.new(conf)
  7. local self = setmetatable({}, WebSocketClient)
  8. local conf = conf or {}
  9. self.uri = conf.uri or nil
  10. self.ws = nil
  11. -- Set custom callback functions if provided
  12. self.on_connected = conf.on_connected or self.on_connected
  13. self.on_disconnected = conf.on_disconnected or self.on_disconnected
  14. self.on_received = conf.on_received or self.on_received
  15. self:connect()
  16. copas.addthread(function() self:receive() end)
  17. return self
  18. end
  19. function WebSocketClient:connect()
  20. self.ws = websocket.new_from_uri(self.uri)
  21. assert(self.ws:connect())
  22. self:on_connected()
  23. end
  24. function WebSocketClient:disconnect()
  25. if self.ws then
  26. self.ws:close()
  27. self:on_disconnected()
  28. end
  29. end
  30. function WebSocketClient:send(data)
  31. data = data or {}
  32. local commandAPI = data.command or 'error'
  33. local dataAPI = data.body or nil
  34. local finalData = nil
  35. if type(dataAPI) == 'table' then
  36. finalData = cjson.encode(dataAPI)
  37. else
  38. finalData = dataAPI or 'Empty'
  39. end
  40. -- print(commandAPI)
  41. -- print(dataAPI)
  42. local message = {
  43. event = commandAPI,
  44. data = finalData
  45. }
  46. local message_json = cjson.encode(message)
  47. if self.ws then
  48. assert(self.ws:send(message_json))
  49. end
  50. end
  51. function WebSocketClient:receive()
  52. while true do
  53. local data, opcode, is_fin = self.ws:receive()
  54. if data then
  55. self:on_received(data)
  56. if data == "close_connection" then
  57. self:disconnect()
  58. break
  59. end
  60. else
  61. self:on_disconnected()
  62. break
  63. end
  64. copas.sleep(0)
  65. end
  66. end
  67. function WebSocketClient:on_connected()
  68. print("Connected to the server.")
  69. end
  70. function WebSocketClient:on_disconnected()
  71. print("Disconnected from the server.")
  72. while true do
  73. print("Attempting to reconnect...")
  74. local success, err = pcall(self.connect, self)
  75. if success then
  76. print("Reconnected to the server.")
  77. copas.addthread(function() self:receive() end)
  78. break
  79. else
  80. print("Failed to reconnect, error: " .. tostring(err))
  81. print("Retrying in 5 seconds...")
  82. copas.sleep(5) -- Wait for 5 seconds before attempting to reconnect
  83. end
  84. end
  85. end
  86. function WebSocketClient:on_received(data)
  87. print("Received data:", data)
  88. end
  89. return WebSocketClient