whoami1337 1 year ago
parent
commit
cf465470c6
2 changed files with 55 additions and 4 deletions
  1. 24 1
      main.lua
  2. 31 3
      websocket.lua

+ 24 - 1
main.lua

@@ -1,9 +1,32 @@
 local copas = require "copas"
 local copas = require "copas"
+local socket = require "socket"
+local cjson = require "cjson"
+
 local WebSocketClient = require('websocket')
 local WebSocketClient = require('websocket')
 
 
 
 
+
 local client = WebSocketClient.new({
 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()
 copas.loop()

+ 31 - 3
websocket.lua

@@ -35,10 +35,25 @@ function WebSocketClient:disconnect()
     end
     end
 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 = {
     local message = {
-        event = command,
-        data = data
+        event = commandAPI,
+        data = finalData
     }
     }
 
 
     local message_json = cjson.encode(message)
     local message_json = cjson.encode(message)
@@ -71,6 +86,19 @@ end
 
 
 function WebSocketClient:on_disconnected()
 function WebSocketClient:on_disconnected()
     print("Disconnected from the server.")
     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
 end
 
 
 function WebSocketClient:on_received(data)
 function WebSocketClient:on_received(data)