whoami1337 1 년 전
부모
커밋
cf465470c6
2개의 변경된 파일55개의 추가작업 그리고 4개의 파일을 삭제
  1. 24 1
      main.lua
  2. 31 3
      websocket.lua

+ 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)