forked from Reselim/roblox-long-polling
-
Notifications
You must be signed in to change notification settings - Fork 4
/
client.lua
100 lines (74 loc) · 1.97 KB
/
client.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
local HttpService = game:GetService("HttpService")
local Connection = {}
Connection.__index = Connection
function Connection.new(options)
local self = setmetatable({options = options}, Connection)
self._events = {}
return self
end
function Connection:_url(path)
return "http" .. (self.secure and "s" or "") .. "://" .. (self.host .. "/" .. path):gsub("//+", "/")
end
-- Connect
function Connection:connect(host, secure)
host = host:gsub("^https?://", "")
self.host = host
self.secure = not not secure
local setValue
if (self.options ~= nil ) then
setValue = self.options.apiKey or false
end
local json = HttpService:RequestAsync(
{
Url = self:_url("/connect"),
Method = "GET",
Headers = {
["Authorization"] = setValue
}
}
)
local response = HttpService:JSONDecode(json.Body)
if response.id then
self.Id = response.id
self._headers = { ["Connection-Id"] = response.id }
self._connected = true
self:_recieve()
end
end
function Connection:disconnect()
self._connected = false
HttpService:GetAsync(self:_url("/disconnect"), true, self._headers)
end
-- Events
function Connection:_getEvent(target)
if not self._events[target] then
self._events[target] = Instance.new("BindableEvent")
end
return self._events[target]
end
function Connection:_emit(target, data)
self:_getEvent(target):Fire(data)
end
function Connection:on(target, func)
return self:_getEvent(target).Event:Connect(func)
end
-- Data
function Connection:_recieve()
if self._connected then
spawn(function()
local json = HttpService:GetAsync(self:_url("/data"), true, self._headers)
local response = HttpService:JSONDecode(json)
for _, message in pairs(response) do
self:_emit(message.t, message.d)
end
self:_recieve()
end)
end
end
function Connection:send(target, data)
spawn(function()
local body = HttpService:JSONEncode({ t = target, d = data })
HttpService:PostAsync(self:_url("/data"), body, nil, nil, self._headers)
end)
end
return Connection