1
0

2 Commits 8aa52e5a0a ... c3109932c0

Autor SHA1 Mensagem Data
  whoami1337 c3109932c0 fix readme há 1 ano atrás
  whoami1337 cf465470c6 fixeds há 1 ano atrás
3 ficheiros alterados com 56 adições e 5 exclusões
  1. 1 1
      README.md
  2. 24 1
      main.lua
  3. 31 3
      websocket.lua

+ 1 - 1
README.md

@@ -26,5 +26,5 @@ on_received(data) -> callback of recevied messages from ws server
 function WebSocketClient:send(command, data)
 
 command -> string,
-data -> any
+data -> any (auto-converted)
 ```

+ 24 - 1
main.lua

@@ -1,9 +1,32 @@
 local copas = require "copas"
+local socket = require "socket"
+local cjson = require "cjson"
+
 local WebSocketClient = require('websocket')
 
 
+
 local client = WebSocketClient.new({
-  uri = "http://localhost:3000",
+  uri = "http://localhost:3000"
 })
 
+function myFunction()
+  local testJSON = {
+    id = 123,
+    price = 0,
+    name = 'Alex',
+    volume = 0
+  }
+
+  -- print(type(testJSON) == 'table')
+  client:send({
+    command = 'orders',
+    body = testJSON
+  })
+end
+
+-- Sleep for 2 seconds (2000 ms)
+socket.sleep(5)
+myFunction()
+
 copas.loop()

+ 31 - 3
websocket.lua

@@ -35,10 +35,25 @@ function WebSocketClient:disconnect()
     end
 end
 
-function WebSocketClient:send(command, data)
+function WebSocketClient:send(data)
+    data = data or {}
+
+    local commandAPI = data.command or 'error'
+    local dataAPI = data.body or nil
+    local finalData = nil
+
+    if type(dataAPI) == 'table' then
+        finalData = cjson.encode(dataAPI)
+    else
+        finalData = dataAPI or 'Empty'
+    end
+
+    -- print(commandAPI)
+    -- print(dataAPI)
+
     local message = {
-        event = command,
-        data = data
+        event = commandAPI,
+        data = finalData
     }
 
     local message_json = cjson.encode(message)
@@ -71,6 +86,19 @@ end
 
 function WebSocketClient:on_disconnected()
     print("Disconnected from the server.")
+    while true do
+        print("Attempting to reconnect...")
+        local success, err = pcall(self.connect, self)
+        if success then
+            print("Reconnected to the server.")
+            copas.addthread(function() self:receive() end)
+            break
+        else
+            print("Failed to reconnect, error: " .. tostring(err))
+            print("Retrying in 5 seconds...")
+            copas.sleep(5) -- Wait for 5 seconds before attempting to reconnect
+        end
+    end
 end
 
 function WebSocketClient:on_received(data)