websocket.lua 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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(command, data)
  31. local message = {
  32. event = command,
  33. data = data
  34. }
  35. local message_json = cjson.encode(message)
  36. if self.ws then
  37. assert(self.ws:send(message_json))
  38. end
  39. end
  40. function WebSocketClient:receive()
  41. while true do
  42. local data, opcode, is_fin = self.ws:receive()
  43. if data then
  44. self:on_received(data)
  45. if data == "close_connection" then
  46. self:disconnect()
  47. break
  48. end
  49. else
  50. self:on_disconnected()
  51. break
  52. end
  53. copas.sleep(0)
  54. end
  55. end
  56. function WebSocketClient:on_connected()
  57. print("Connected to the server.")
  58. end
  59. function WebSocketClient:on_disconnected()
  60. print("Disconnected from the server.")
  61. end
  62. function WebSocketClient:on_received(data)
  63. print("Received data:", data)
  64. end
  65. return WebSocketClient