WebsocketClient/WebSocket.lua
2024-09-04 08:43:54 -06:00

88 lines
2.2 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 response, status = server:RequestAsync({
["Url"] = BaseUrl .. "/api/connect/" .. JobId,
["Method"] = "PUT",
["Body"] = server:JSONEncode({["url"] = dict.url}),
["Headers"] = {["Content-Type"] = "application/json"}
})
if response.Success then
local id = response.Body
local function sendMessage(msg)
wait()
local resp = server:RequestAsync({
["Url"] = BaseUrl .. "/api/send/" .. JobId .."/"..id,
["Method"] = "POST",
["Body"] = server:JSONEncode({["data"] = msg}),
["Headers"] = {["Content-Type"] = "application/json"}
})
if not resp.Success then
error("Error Sending Message: " .. resp.StatusCode .. " " .. resp.StatusMessage)
end
end
local function close()
server:RequestAsync({
["Url"] = BaseUrl .. "/api/close/" .. JobId .. "/" .. id,
["Method"] = "DELETE"
})
end
local loop = coroutine.create(function()
while wait(0.1) do
print("poll")
local response = server:RequestAsync({
["Url"] = BaseUrl .. "/api/poll/"..JobId.."/".. id,
["Method"] = "GET"
})
if response.Success then
local msg = response.Body
if notExists(messages, msg) then
table.insert(messages, msg)
if notEmpty(msg) then
onMessage(msg)
end
end
else
error("Error Polling Messages: " .. response.StatusCode .. " " .. response.StatusMessage)
end
end
end)
coroutine.resume(loop)
game:BindToClose(close)
return {
sendMessage = sendMessage,
onMessage = onMessage,
close = close
}
else
error("Error Connecting to Websocket Server: " .. response.StatusCode .. " " .. response.StatusMessage)
end
end
return ws