1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- local websocket = require "http.websocket"
- local copas = require "copas"
- local cjson = require "cjson"
- WebSocketClient = {}
- WebSocketClient.__index = WebSocketClient
- function WebSocketClient.new(conf)
- local self = setmetatable({}, WebSocketClient)
- local conf = conf or {}
- self.uri = conf.uri or nil
- self.ws = nil
- -- Set custom callback functions if provided
- self.on_connected = conf.on_connected or self.on_connected
- self.on_disconnected = conf.on_disconnected or self.on_disconnected
- self.on_received = conf.on_received or self.on_received
- self:connect()
- copas.addthread(function() self:receive() end)
-
- return self
- end
- function WebSocketClient:connect()
- self.ws = websocket.new_from_uri(self.uri)
- assert(self.ws:connect())
- self:on_connected()
- end
- function WebSocketClient:disconnect()
- if self.ws then
- self.ws:close()
- self:on_disconnected()
- end
- end
- function WebSocketClient:send(command, data)
- local message = {
- event = command,
- data = data
- }
- local message_json = cjson.encode(message)
- if self.ws then
- assert(self.ws:send(message_json))
- end
- end
- function WebSocketClient:receive()
- while true do
- local data, opcode, is_fin = self.ws:receive()
- if data then
- self:on_received(data)
- if data == "close_connection" then
- self:disconnect()
- break
- end
- else
- self:on_disconnected()
- break
- end
- copas.sleep(0)
- end
- end
- function WebSocketClient:on_connected()
- print("Connected to the server.")
- end
- function WebSocketClient:on_disconnected()
- print("Disconnected from the server.")
- end
- function WebSocketClient:on_received(data)
- print("Received data:", data)
- end
- return WebSocketClient
|