WebsocketClient/WebSocket.lua
2024-09-04 07:46:01 -06:00

66 lines
1.4 KiB
Lua

local Base64 = require(script.Base64)
local JobId = game:GetService('HttpService'):GenerateGUID(false)
print("jobid is " .. JobId)
local BaseUrl = "https://sock.kcadev.org"
local atob = Base64.atob
local btoa = Base64.btoa
local messages = {}
local function notExists(whichArray, itemName)
if (table.find(whichArray, itemName)) then
return false
else
return true
end
end
local function notEmpty(s)
return s ~= nil or s ~= '' or s ~= " "
end
local ws = function (dict)
local onMessage = dict.onMessage or function(msg)
print(msg)
end
local server = game:GetService('HttpService')
local id = server:RequestAsync({
["Url"] = BaseUrl .. "api/connect/" .. JobId,
["Method"] = "PUT",
["Body"] = dict.url
}).Body
print(id)
print(typeof(id))
local function sendMessage(msg)
wait()
server:PostAsync(BaseUrl .. "api/send/" .. JobId .."/"..id, msg)
end
local function close()
server:RequestAsync({
["Url"] = BaseUrl .. "api/close/" .. JobId .. "/" .. id,
["Method"] = "DELETE"
})
end
local loop = coroutine.create(function()
while wait(50 / 1000) do
local msg = server:GetAsync(BaseUrl .. "api/poll/"..JobId.."/"..id)
if notExists(messages, msg) then
table.insert(messages, msg)
if notEmpty(msg) then
onMessage(msg)
end
end
end
end)
coroutine.resume(loop)
game:BindToClose(close)
return {
sendMessage = sendMessage,
onMessage = onMessage,
close = close
}
end
return ws