forked from pilsprog/skyport-lovegraphics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LUBE.lua
449 lines (399 loc) · 11.2 KB
/
LUBE.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
--[[ LICENSE
-- Following is the MIT license as found on
-- http://www.opensource.org/licenses/mit-license.php .
Copyright (c) 2011 Bart van Strien
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]
local socket = require "socket"
-- We use Class Commons
assert(common and common.class, "A Class Commons implementation is required")
local client = {}
-- A generic client class
-- Implementations are required to implement the following functions:
-- * createSocket() --> Put a socket object in self.socket
-- * success, err = _connect() --> Connect the socket to self.host and self.port
-- * _disconnect() --> Disconnect the socket
-- * success, err = _send(data) --> Send data to the server
-- * message, err = _receive() --> Receive a message from the server
-- * setOption(option, value) --> Set a socket option, options being one of the following:
-- - "broadcast" --> Allow broadcast packets.
-- And they also have to set _implemented to evaluate to true.
--
-- Note that all implementations should have a 0 timeout, except for connecting.
function client:init()
assert(self._implemented, "Can't use a generic client object directly, please provide an implementation.")
-- 'Initialize' our variables
self.host = nil
self.port = nil
self.connected = false
self.socket = nil
self.callbacks = {
recv = nil
}
self.handshake = nil
self.ping = nil
end
function client:setPing(enabled, time, msg)
-- If ping is enabled, create a self.ping
-- and set the time and the message in it,
-- but most importantly, keep the time.
-- If disabled, set self.ping to nil.
if enabled then
self.ping = {
time = time,
msg = msg,
timer = time
}
else
self.ping = nil
end
end
function client:connect(host, port, dns)
-- Verify our inputs.
if not host or not port then
return false, "Invalid arguments"
end
-- Resolve dns if needed (dns is true by default).
if dns ~= false then
local ip = socket.dns.toip(host)
if not ip then
return false, "DNS lookup failed for " .. host
end
host = ip
end
-- Set it up for our new connection.
self:createSocket()
self.host = host
self.port = port
-- Ask our implementation to actually connect.
local success, err = self:_connect()
if not success then
self.host = nil
self.port = nil
return false, err
end
self.connected = true
-- Send our handshake if we have one.
if self.handshake then
self:send(self.handshake .. "+\n")
end
return true
end
function client:disconnect()
if self.connected then
self:send(self.handshake .. "-\n")
self:_disconnect()
self.host = nil
self.port = nil
end
end
function client:send(data)
-- Check if we're connected and pass it on.
if not self.connected then
return false, "Not connected"
end
return self:_send(data)
end
function client:receive()
-- Check if we're connected and pass it on.
if not self.connected then
return false, "Not connected"
end
return self:_receive()
end
function client:update(dt)
if not self.connected then return end
assert(dt, "Update needs a dt!")
-- First, let's handle ping messages.
if self.ping then
self.ping.timer = self.ping.timer + dt
if self.ping.timer > self.ping.time then
self:_send(self.ping.msg)
self.ping.timer = 0
end
end
-- If a recv callback is set, let's grab
-- all incoming messages. If not, leave
-- them in the queue.
if self.callbacks.recv then
local data, err = self:_receive()
while data do
self.callbacks.recv(data)
data, err = self:_receive()
end
end
end
local server = {}
-- A generic server class
-- Implementations are required to implement the following functions:
-- * createSocket() --> Put a socket object in self.socket.
-- * _listen() --> Listen on self.port. (All interfaces.)
-- * send(data, clientid) --> Send data to clientid, or everyone if clientid is nil.
-- * data, clientid = receive() --> Receive data.
-- * accept() --> Accept all waiting clients.
-- And they also have to set _implemented to evaluate to true.
-- Note that all functions should have a 0 timeout.
function server:init()
assert(self._implemented, "Can't use a generic server object directly, please provide an implementation.")
-- 'Initialize' our variables
-- Some more initialization.
self.clients = {}
self.handshake = nil
self.callbacks = {
recv = nil,
connect = nil,
disconnect = nil,
}
self.ping = nil
self.port = nil
end
function server:setPing(enabled, time, msg)
-- Set self.ping if enabled with time and msg,
-- otherwise set it to nil.
if enabled then
self.ping = {
time = time,
msg = msg
}
else
self.ping = nil
end
end
function server:listen(port)
-- Create a socket, set the port and listen.
self:createSocket()
self.port = port
self:_listen()
end
function server:update(dt)
assert(dt, "Update needs a dt!")
-- Accept all waiting clients.
self:accept()
-- Start handling messages.
local data, clientid = self:receive()
while data do
local hs, conn = data:match("^(.+)([%+%-])\n?$")
if hs == self.handshake and conn == "+" then
-- If we already knew the client, ignore.
if not self.clients[clientid] then
self.clients[clientid] = {ping = -dt}
if self.callbacks.connect then
self.callbacks.connect(clientid)
end
end
elseif hs == self.handshake and conn == "-" then
-- Ignore unknown clients (perhaps they timed out before?).
if self.clients[clientid] then
self.clients[clientid] = nil
if self.callbacks.disconnect then
self.callbacks.disconnect(clientid)
end
end
elseif not self.ping or data ~= self.ping.msg then
-- Filter out ping messages and call the recv callback.
if self.callbacks.recv then
self.callbacks.recv(data, clientid)
end
end
-- Mark as 'ping receive', -dt because dt is added after.
-- (Which means a net result of 0.)
if self.clients[clientid] then
self.clients[clientid].ping = -dt
end
data, clientid = self:receive()
end
if self.ping then
-- If we ping then up all the counters.
-- If it exceeds the limit we set, disconnect the client.
for i, v in pairs(self.clients) do
v.ping = v.ping + dt
if v.ping > self.ping.time then
self.clients[i] = nil
if self.callbacks.disconnect then
self.callbacks.disconnect(i)
end
end
end
end
end
-- And now, implementations!
-- First, UDP.
local udpClient = {}
udpClient._implemented = true
function udpClient:createSocket()
self.socket = socket.udp()
self.socket:settimeout(0)
end
function udpClient:_connect()
-- We're connectionless,
-- guaranteed success!
return true
end
function udpClient:_disconnect()
-- Well, that's easy.
end
function udpClient:_send(data)
return self.socket:sendto(data, self.host, self.port)
end
function udpClient:_receive()
local data, ip, port = self.socket:receivefrom()
if ip == self.host and port == self.port then
return data
end
return false, "Unknown remote sent data."
end
function udpClient:setOption(option, value)
if option == "broadcast" then
self.socket:setoption("broadcast", not not value)
end
end
local udpServer = {}
udpServer._implemented = true
function udpServer:createSocket()
self.socket = socket.udp()
self.socket:settimeout(0)
end
function udpServer:_listen()
self.socket:setsockname("*", self.port)
end
function udpServer:send(data, clientid)
-- We conviently use ip:port as clientid.
if clientid then
local ip, port = clientid:match("^(.-):(%d+)$")
self.socket:sendto(data, ip, tonumber(port))
else
for clientid, _ in pairs(self.clients) do
local ip, port = clientid:match("^(.-):(%d+)$")
self.socket:sendto(data, ip, tonumber(port))
end
end
end
function udpServer:receive()
local data, ip, port = self.socket:receivefrom()
if data then
local id = ip .. ":" .. port
return data, id
end
return nil, "No message."
end
function udpServer:accept()
end
-- But also, TCP.
local tcpClient = {}
tcpClient._implemented = true
function tcpClient:createSocket()
self.socket = socket.tcp()
self.socket:settimeout(0)
end
function tcpClient:_connect()
self.socket:settimeout(5)
local success, err = self.socket:connect(self.host, self.port)
self.socket:settimeout(0)
return success, err
end
function tcpClient:_disconnect()
self.socket:shutdown()
end
function tcpClient:_send(data)
return self.socket:send(data)
end
function tcpClient:_receive()
local packet = ""
local data, _, partial = self.socket:receive(8192)
while data do
packet = packet .. data
data, _, partial = self.socket:receive(8192)
end
if not data and partial then
packet = packet .. partial
end
if packet ~= "" then
return packet
end
return nil, "No messages"
end
function tcpClient:setoption(option, value)
if option == "broadcast" then
self.socket:setoption("broadcast", not not value)
end
end
local tcpServer = {}
tcpServer._implemented = true
function tcpServer:createSocket()
self._socks = {}
self.socket = socket.tcp()
self.socket:settimeout(0)
self.socket:setoption("reuseaddr", true)
end
function tcpServer:_listen()
self.socket:bind("*", self.port)
self.socket:listen(5)
end
function tcpServer:send(data, clientid)
-- This time, the clientip is the client socket.
if clientid then
clientid:send(data)
else
for sock, _ in pairs(self.clients) do
sock:send(data)
end
end
end
function tcpServer:receive()
for sock, _ in pairs(self.clients) do
local packet = ""
local data, _, partial = sock:receive(8192)
while data do
packet = packet .. data
data, _, partial = sock:receive(8192)
end
if not data and partial then
packet = packet .. partial
end
if packet ~= "" then
return packet, sock
end
end
for i, sock in pairs(self._socks) do
local data = sock:receive()
if data then
local hs, conn = data:match("^(.+)([%+%-])\n?$")
if hs == self.handshake and conn == "+" then
self._socks[i] = nil
return data, sock
end
end
end
return nil, "No messages."
end
function tcpServer:accept()
local sock = self.socket:accept()
while sock do
sock:settimeout(0)
self._socks[#self._socks+1] = sock
sock = self.socket:accept()
end
end
-- Create our classes:
lube = {}
lube.Client = common.class("lube.Client", client)
lube.udpClient = common.class("lube.udpClient", udpClient, lube.Client)
lube.tcpClient = common.class("lube.tcpClient", tcpClient, lube.Client)
lube.Server = common.class("lube.Server", server)
lube.udpServer = common.class("lube.udpServer", udpServer, lube.Server)
lube.tcpServer = common.class("lube.tcpServer", tcpServer, lube.Server)