whoami1337 1 tahun lalu
induk
melakukan
85166b0303
3 mengubah file dengan 116 tambahan dan 0 penghapusan
  1. 1 0
      .gitignore
  2. 35 0
      main.lua
  3. 80 0
      websocket.lua

+ 1 - 0
.gitignore

@@ -0,0 +1 @@
+.vscode

+ 35 - 0
main.lua

@@ -0,0 +1,35 @@
+local copas = require "copas"
+local cjson = require("cjson")
+local WebSocketClient = require('websocket')
+
+
+-- local client = WebSocketClient.new("ws://localhost:1337", on_received = custom_on_received)
+local client = WebSocketClient.new({
+  uri = "http://localhost:3000",
+})
+print("test")
+function delayed_function()
+  local message = {
+    event = "demo",
+    data = "Hello from Lua!"
+  }
+  local message_json = cjson.encode(message)
+  client:send(message_json)
+end
+
+print("test")
+delayed_function();
+copas.loop()
+
+
+-- events: (вызов функций)
+--connect
+--disconnect
+--received
+
+-- send
+ 
+-- будет 2 типа сообщенгий
+-- приветственное сообщение
+-- сообщения заявок
+-- обезлитченные сделки

+ 80 - 0
websocket.lua

@@ -0,0 +1,80 @@
+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