-
Notifications
You must be signed in to change notification settings - Fork 0
/
sock.lua
1413 lines (1223 loc) · 45.8 KB
/
sock.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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--- A Lua networking library for LÖVE games.
-- * [Source code](https://github.com/camchenry/sock.lua)
-- * [Examples](https://github.com/camchenry/sock.lua/tree/master/examples)
-- @module sock
local sock = {
_VERSION = 'sock.lua v0.3.0',
_DESCRIPTION = 'A Lua networking library for LÖVE games',
_URL = 'https://github.com/camchenry/sock.lua',
_LICENSE = [[
MIT License
Copyright (c) 2016 Cameron McHenry
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 enet = require "enet"
-- Current folder trick
-- http://kiki.to/blog/2014/04/12/rule-5-beware-of-multiple-files/
local currentFolder = (...):gsub('%.[^%.]+$', '')
local bitserLoaded = false
if bitser then
bitserLoaded = true
end
-- Try to load some common serialization libraries
-- This is for convenience, you may still specify your own serializer
if not bitserLoaded then
bitserLoaded, bitser = pcall(require, "bitser")
end
-- Try to load relatively
if not bitserLoaded then
bitserLoaded, bitser = pcall(require, currentFolder .. ".bitser")
end
-- links variables to keys based on their order
-- note that it only works for boolean and number values, not strings
local function zipTable(items, keys, event)
local data = {}
-- convert variable at index 1 into the value for the key value at index 1, and so on
for i, value in ipairs(items) do
local key = keys[i]
if not key then
error("Event '"..event.."' missing data key. Is the schema different between server and client?")
end
data[key] = value
end
return data
end
--- All of the possible connection statuses for a client connection.
-- @see Client:getState
sock.CONNECTION_STATES = {
"disconnected", -- Disconnected from the server.
"connecting", -- In the process of connecting to the server.
"acknowledging_connect", --
"connection_pending", --
"connection_succeeded", --
"connected", -- Successfully connected to the server.
"disconnect_later", -- Disconnecting, but only after sending all queued packets.
"disconnecting", -- In the process of disconnecting from the server.
"acknowledging_disconnect", --
"zombie", --
"unknown", --
}
--- States that represent the client connecting to a server.
sock.CONNECTING_STATES = {
"connecting", -- In the process of connecting to the server.
"acknowledging_connect", --
"connection_pending", --
"connection_succeeded", --
}
--- States that represent the client disconnecting from a server.
sock.DISCONNECTING_STATES = {
"disconnect_later", -- Disconnecting, but only after sending all queued packets.
"disconnecting", -- In the process of disconnecting from the server.
"acknowledging_disconnect", --
}
--- Valid modes for sending messages.
sock.SEND_MODES = {
"reliable", -- Message is guaranteed to arrive, and arrive in the order in which it is sent.
"unsequenced", -- Message has no guarantee on the order that it arrives.
"unreliable", -- Message is not guaranteed to arrive.
}
local function isValidSendMode(mode)
for _, validMode in ipairs(sock.SEND_MODES) do
if mode == validMode then
return true
end
end
return false
end
local Logger = {}
local Logger_mt = {__index = Logger}
local function newLogger(source)
local logger = setmetatable({
source = source,
messages = {},
-- Makes print info more concise, but should still log the full line
shortenLines = true,
-- Print all incoming event data
printEventData = false,
printErrors = true,
printWarnings = true,
}, Logger_mt)
return logger
end
function Logger:log(event, data)
local time = os.date("%X") -- something like 24:59:59
local shortLine = ("[%s] %s"):format(event, data)
local fullLine = ("[%s][%s][%s] %s"):format(self.source, time, event, data)
-- The printed message may or may not be the full message
local line = fullLine
if self.shortenLines then
line = shortLine
end
if self.printEventData then
print(line)
elseif self.printErrors and event == "error" then
print(line)
elseif self.printWarnings and event == "warning" then
print(line)
end
-- The logged message is always the full message
table.insert(self.messages, fullLine)
-- TODO: Dump to a log file
end
local Listener = {}
local Listener_mt = {__index = Listener}
local function newListener()
local listener = setmetatable({
triggers = {},
schemas = {},
}, Listener_mt)
return listener
end
-- Adds a callback to a trigger
-- Returns: the callback function
function Listener:addCallback(event, callback)
if not self.triggers[event] then
self.triggers[event] = {}
end
table.insert(self.triggers[event], callback)
return callback
end
-- Removes a callback on a given trigger
-- Returns a boolean indicating if the callback was removed
function Listener:removeCallback(callback)
for _, triggers in pairs(self.triggers) do
for i, trigger in pairs(triggers) do
if trigger == callback then
table.remove(triggers, i)
return true
end
end
end
return false
end
-- Accepts: event (string), schema (table)
-- Returns: nothing
function Listener:setSchema(event, schema)
self.schemas[event] = schema
end
-- Activates all callbacks for a trigger
-- Returns a boolean indicating if any callbacks were triggered
function Listener:trigger(event, data, client)
if self.triggers[event] then
for _, trigger in pairs(self.triggers[event]) do
-- Event has a pre-existing schema defined
if self.schemas[event] then
data = zipTable(data, self.schemas[event], event)
end
trigger(data, client)
end
return true
else
return false
end
end
--- Manages all clients and receives network events.
-- @type Server
local Server = {}
local Server_mt = {__index = Server}
--- Check for network events and handle them.
function Server:update()
local event = self.host:service(self.messageTimeout)
while event do
if event.type == "connect" then
local eventClient = sock.newClient(event.peer)
eventClient:setSerialization(self.serialize, self.deserialize)
table.insert(self.peers, event.peer)
table.insert(self.clients, eventClient)
self:_activateTriggers("connect", event.data, eventClient)
self:log(event.type, tostring(event.peer) .. " connected")
elseif event.type == "receive" then
local eventName, data = self:__unpack(event.data)
local eventClient = self:getClient(event.peer)
self:_activateTriggers(eventName, data, eventClient)
self:log(eventName, data)
elseif event.type == "disconnect" then
-- remove from the active peer list
for i, peer in pairs(self.peers) do
if peer == event.peer then
table.remove(self.peers, i)
end
end
local eventClient = self:getClient(event.peer)
for i, client in pairs(self.clients) do
if client == eventClient then
table.remove(self.clients, i)
end
end
self:_activateTriggers("disconnect", event.data, eventClient)
self:log(event.type, tostring(event.peer) .. " disconnected")
end
event = self.host:service(self.messageTimeout)
end
end
-- Creates the unserialized message that will be used in callbacks
-- In: serialized message (string)
-- Out: event (string), data (mixed)
function Server:__unpack(data)
if not self.deserialize then
self:log("error", "Can't deserialize message: deserialize was not set")
error("Can't deserialize message: deserialize was not set")
end
local message = self.deserialize(data)
local eventName, data = message[1], message[2]
return eventName, data
end
-- Creates the serialized message that will be sent over the network
-- In: event (string), data (mixed)
-- Out: serialized message (string)
function Server:__pack(event, data)
local message = {event, data}
local serializedMessage
if not self.serialize then
self:log("error", "Can't serialize message: serialize was not set")
error("Can't serialize message: serialize was not set")
end
-- 'Data' = binary data class in Love
if type(data) == "userdata" and data.type and data:typeOf("Data") then
message[2] = data:getString()
serializedMessage = self.serialize(message)
else
serializedMessage = self.serialize(message)
end
return serializedMessage
end
--- Send a message to all clients, except one.
-- Useful for when the client does something locally, but other clients
-- need to be updated at the same time. This way avoids duplicating objects by
-- never sending its own event to itself in the first place.
-- @tparam Client client The client to not receive the message.
-- @tparam string event The event to trigger with this message.
-- @param data The data to send.
function Server:sendToAllBut(client, event, data)
local serializedMessage = self:__pack(event, data)
for _, p in pairs(self.peers) do
if p ~= client.connection then
self.packetsSent = self.packetsSent + 1
p:send(serializedMessage, self.sendChannel, self.sendMode)
end
end
self:resetSendSettings()
end
--- Send a message to all clients.
-- @tparam string event The event to trigger with this message.
-- @param data The data to send.
--@usage
--server:sendToAll("gameStarting", true)
function Server:sendToAll(event, data)
local serializedMessage = self:__pack(event, data)
self.packetsSent = self.packetsSent + #self.peers
self.host:broadcast(serializedMessage, self.sendChannel, self.sendMode)
self:resetSendSettings()
end
--- Send a message to a single peer. Useful to send data to a newly connected player
-- without sending to everyone who already received it.
-- @tparam enet_peer peer The enet peer to receive the message.
-- @tparam string event The event to trigger with this message.
-- @param data data to send to the peer.
--@usage
--server:sendToPeer(peer, "initialGameInfo", {...})
function Server:sendToPeer(peer, event, data)
local serializedMessage = self:__pack(event, data)
self.packetsSent = self.packetsSent + 1
peer:send(serializedMessage, self.sendChannel, self.sendMode)
self:resetSendSettings()
end
--- Add a callback to an event.
-- @tparam string event The event that will trigger the callback.
-- @tparam function callback The callback to be triggered.
-- @treturn function The callback that was passed in.
--@usage
--server:on("connect", function(data, client)
-- print("Client connected!")
--end)
function Server:on(event, callback)
return self.listener:addCallback(event, callback)
end
function Server:_activateTriggers(event, data, client)
local result = self.listener:trigger(event, data, client)
self.packetsReceived = self.packetsReceived + 1
if not result then
self:log("warning", "Tried to activate trigger: '" .. tostring(event) .. "' but it does not exist.")
end
end
--- Remove a specific callback for an event.
-- @tparam function callback The callback to remove.
-- @treturn boolean Whether or not the callback was removed.
--@usage
--local callback = server:on("chatMessage", function(message)
-- print(message)
--end)
--server:removeCallback(callback)
function Server:removeCallback(callback)
return self.listener:removeCallback(callback)
end
--- Log an event.
-- Alias for Server.logger:log.
-- @tparam string event The type of event that happened.
-- @tparam string data The message to log.
--@usage
--if somethingBadHappened then
-- server:log("error", "Something bad happened!")
--end
function Server:log(event, data)
return self.logger:log(event, data)
end
--- Reset all send options to their default values.
function Server:resetSendSettings()
self.sendMode = self.defaultSendMode
self.sendChannel = self.defaultSendChannel
end
--- Enables an adaptive order-2 PPM range coder for the transmitted data of all peers. Both the client and server must both either have compression enabled or disabled.
--
-- Note: lua-enet does not currently expose a way to disable the compression after it has been enabled.
function Server:enableCompression()
return self.host:compress_with_range_coder()
end
--- Destroys the server and frees the port it is bound to.
function Server:destroy()
self.host:destroy()
end
--- Set the send mode for the next outgoing message.
-- The mode will be reset after the next message is sent. The initial default
-- is "reliable".
-- @tparam string mode A valid send mode.
-- @see SEND_MODES
-- @usage
--server:setSendMode("unreliable")
--server:sendToAll("playerState", {...})
function Server:setSendMode(mode)
if not isValidSendMode(mode) then
self:log("warning", "Tried to use invalid send mode: '" .. mode .. "'. Defaulting to reliable.")
mode = "reliable"
end
self.sendMode = mode
end
--- Set the default send mode for all future outgoing messages.
-- The initial default is "reliable".
-- @tparam string mode A valid send mode.
-- @see SEND_MODES
function Server:setDefaultSendMode(mode)
if not isValidSendMode(mode) then
self:log("error", "Tried to set default send mode to invalid mode: '" .. mode .. "'")
error("Tried to set default send mode to invalid mode: '" .. mode .. "'")
end
self.defaultSendMode = mode
end
--- Set the send channel for the next outgoing message.
-- The channel will be reset after the next message. Channels are zero-indexed
-- and cannot exceed the maximum number of channels allocated. The initial
-- default is 0.
-- @tparam number channel Channel to send data on.
-- @usage
--server:setSendChannel(2) -- the third channel
--server:sendToAll("importantEvent", "The message")
function Server:setSendChannel(channel)
if channel > (self.maxChannels - 1) then
self:log("warning", "Tried to use invalid channel: " .. channel .. " (max is " .. self.maxChannels - 1 .. "). Defaulting to 0.")
channel = 0
end
self.sendChannel = channel
end
--- Set the default send channel for all future outgoing messages.
-- The initial default is 0.
-- @tparam number channel Channel to send data on.
function Server:setDefaultSendChannel(channel)
self.defaultSendChannel = channel
end
--- Set the data schema for an event.
--
-- Schemas allow you to set a specific format that the data will be sent. If the
-- client and server both know the format ahead of time, then the table keys
-- do not have to be sent across the network, which saves bandwidth.
-- @tparam string event The event to set the data schema for.
-- @tparam {string,...} schema The data schema.
-- @usage
-- server = sock.newServer(...)
-- client = sock.newClient(...)
--
-- -- Without schemas
-- client:send("update", {
-- x = 4,
-- y = 100,
-- vx = -4.5,
-- vy = 23.1,
-- rotation = 1.4365,
-- })
-- server:on("update", function(data, client)
-- -- data = {
-- -- x = 4,
-- -- y = 100,
-- -- vx = -4.5,
-- -- vy = 23.1,
-- -- rotation = 1.4365,
-- -- }
-- end)
--
--
-- -- With schemas
-- server:setSchema("update", {
-- "x",
-- "y",
-- "vx",
-- "vy",
-- "rotation",
-- })
-- -- client no longer has to send the keys, saving bandwidth
-- client:send("update", {
-- 4,
-- 100,
-- -4.5,
-- 23.1,
-- 1.4365,
-- })
-- server:on("update", function(data, client)
-- -- data = {
-- -- x = 4,
-- -- y = 100,
-- -- vx = -4.5,
-- -- vy = 23.1,
-- -- rotation = 1.4365,
-- -- }
-- end)
function Server:setSchema(event, schema)
return self.listener:setSchema(event, schema)
end
--- Set the incoming and outgoing bandwidth limits.
-- @tparam number incoming The maximum incoming bandwidth in bytes.
-- @tparam number outgoing The maximum outgoing bandwidth in bytes.
function Server:setBandwidthLimit(incoming, outgoing)
return self.host:bandwidth_limit(incoming, outgoing)
end
--- Set the maximum number of channels.
-- @tparam number limit The maximum number of channels allowed. If it is 0,
-- then the maximum number of channels available on the system will be used.
function Server:setMaxChannels(limit)
self.host:channel_limit(limit)
end
--- Set the timeout to wait for packets.
-- @tparam number timeout Time to wait for incoming packets in milliseconds. The
-- initial default is 0.
function Server:setMessageTimeout(timeout)
self.messageTimeout = timeout
end
--- Set the serialization functions for sending and receiving data.
-- Both the client and server must share the same serialization method.
-- @tparam function serialize The serialization function to use.
-- @tparam function deserialize The deserialization function to use.
-- @usage
--bitser = require "bitser" -- or any library you like
--server = sock.newServer("localhost", 22122)
--server:setSerialization(bitser.dumps, bitser.loads)
function Server:setSerialization(serialize, deserialize)
assert(type(serialize) == "function", "Serialize must be a function, got: '"..type(serialize).."'")
assert(type(deserialize) == "function", "Deserialize must be a function, got: '"..type(deserialize).."'")
self.serialize = serialize
self.deserialize = deserialize
end
--- Gets the Client object associated with an enet peer.
-- @tparam peer peer An enet peer.
-- @treturn Client Object associated with the peer.
function Server:getClient(peer)
for _, client in pairs(self.clients) do
if peer == client.connection then
return client
end
end
end
--- Gets the Client object that has the given connection id.
-- @tparam number connectId The unique client connection id.
-- @treturn Client
function Server:getClientByConnectId(connectId)
for _, client in pairs(self.clients) do
if connectId == client.connectId then
return client
end
end
end
--- Get the Client object that has the given peer index.
-- @treturn Client
function Server:getClientByIndex(index)
for _, client in pairs(self.clients) do
if index == client:getIndex() then
return client
end
end
end
--- Get the enet_peer that has the given index.
-- @treturn enet_peer The underlying enet peer object.
function Server:getPeerByIndex(index)
return self.host:get_peer(index)
end
--- Get the total sent data since the server was created.
-- @treturn number The total sent data in bytes.
function Server:getTotalSentData()
return self.host:total_sent_data()
end
--- Get the total received data since the server was created.
-- @treturn number The total received data in bytes.
function Server:getTotalReceivedData()
return self.host:total_received_data()
end
--- Get the total number of packets (messages) sent since the server was created.
-- Everytime a message is sent or received, the corresponding figure is incremented.
-- Therefore, this is not necessarily an accurate indicator of how many packets were actually
-- exchanged over the network.
-- @treturn number The total number of sent packets.
function Server:getTotalSentPackets()
return self.packetsSent
end
--- Get the total number of packets (messages) received since the server was created.
-- @treturn number The total number of received packets.
-- @see Server:getTotalSentPackets
function Server:getTotalReceivedPackets()
return self.packetsReceived
end
--- Get the last time when network events were serviced.
-- @treturn number Timestamp of the last time events were serviced.
function Server:getLastServiceTime()
return self.host:service_time()
end
--- Get the number of allocated slots for peers.
-- @treturn number Number of allocated slots.
function Server:getMaxPeers()
return self.maxPeers
end
--- Get the number of allocated channels.
-- Channels are zero-indexed, e.g. 16 channels allocated means that the
-- maximum channel that can be used is 15.
-- @treturn number Number of allocated channels.
function Server:getMaxChannels()
return self.maxChannels
end
--- Get the timeout for packets.
-- @treturn number Time to wait for incoming packets in milliseconds.
-- initial default is 0.
function Server:getMessageTimeout()
return self.messageTimeout
end
--- Get the socket address of the host.
-- @treturn string A description of the socket address, in the format
-- "A.B.C.D:port" where A.B.C.D is the IP address of the used socket.
function Server:getSocketAddress()
return self.host:get_socket_address()
end
--- Get the current send mode.
-- @treturn string
-- @see SEND_MODES
function Server:getSendMode()
return self.sendMode
end
--- Get the default send mode.
-- @treturn string
-- @see SEND_MODES
function Server:getDefaultSendMode()
return self.defaultSendMode
end
--- Get the IP address or hostname that the server was created with.
-- @treturn string
function Server:getAddress()
return self.address
end
--- Get the port that the server is hosted on.
-- @treturn number
function Server:getPort()
return self.port
end
--- Get the table of Clients actively connected to the server.
-- @return {Client,...}
function Server:getClients()
return self.clients
end
--- Get the number of Clients that are currently connected to the server.
-- @treturn number The number of active clients.
function Server:getClientCount()
return #self.clients
end
--- Connects to servers.
-- @type Client
local Client = {}
local Client_mt = {__index = Client}
--- Check for network events and handle them.
function Client:update()
local event = self.host:service(self.messageTimeout)
while event do
if event.type == "connect" then
self:_activateTriggers("connect", event.data)
self:log(event.type, "Connected to " .. tostring(self.connection))
elseif event.type == "receive" then
local eventName, data = self:__unpack(event.data)
self:_activateTriggers(eventName, data)
self:log(eventName, data)
elseif event.type == "disconnect" then
self:_activateTriggers("disconnect", event.data)
self:log(event.type, "Disconnected from " .. tostring(self.connection))
end
event = self.host:service(self.messageTimeout)
end
end
--- Connect to the chosen server.
-- Connection will not actually occur until the next time `Client:update` is called.
-- @tparam ?number code A number that can be associated with the connect event.
function Client:connect(code)
-- number of channels for the client and server must match
self.connection = self.host:connect(self.address .. ":" .. self.port, self.maxChannels, code)
self.connectId = self.connection:connect_id()
end
--- Disconnect from the server, if connected. The client will disconnect the
-- next time that network messages are sent.
-- @tparam ?number code A code to associate with this disconnect event.
-- @todo Pass the code into the disconnect callback on the server
function Client:disconnect(code)
code = code or 0
self.connection:disconnect(code)
end
--- Disconnect from the server, if connected. The client will disconnect after
-- sending all queued packets.
-- @tparam ?number code A code to associate with this disconnect event.
-- @todo Pass the code into the disconnect callback on the server
function Client:disconnectLater(code)
code = code or 0
self.connection:disconnect_later(code)
end
--- Disconnect from the server, if connected. The client will disconnect immediately.
-- @tparam ?number code A code to associate with this disconnect event.
-- @todo Pass the code into the disconnect callback on the server
function Client:disconnectNow(code)
code = code or 0
self.connection:disconnect_now(code)
end
--- Forcefully disconnects the client. The server is not notified of the disconnection.
-- @tparam Client client The client to reset.
function Client:reset()
if self.connection then
self.connection:reset()
end
end
-- Creates the unserialized message that will be used in callbacks
-- In: serialized message (string)
-- Out: event (string), data (mixed)
function Client:__unpack(data)
if not self.deserialize then
self:log("error", "Can't deserialize message: deserialize was not set")
error("Can't deserialize message: deserialize was not set")
end
local message = self.deserialize(data)
local eventName, data = message[1], message[2]
return eventName, data
end
-- Creates the serialized message that will be sent over the network
-- In: event (string), data (mixed)
-- Out: serialized message (string)
function Client:__pack(event, data)
local message = {event, data}
local serializedMessage
if not self.serialize then
self:log("error", "Can't serialize message: serialize was not set")
error("Can't serialize message: serialize was not set")
end
-- 'Data' = binary data class in Love
if type(data) == "userdata" and data.type and data:typeOf("Data") then
message[2] = data:getString()
serializedMessage = self.serialize(message)
else
serializedMessage = self.serialize(message)
end
return serializedMessage
end
--- Send a message to the server.
-- @tparam string event The event to trigger with this message.
-- @param data The data to send.
function Client:send(event, data)
local serializedMessage = self:__pack(event, data)
self.connection:send(serializedMessage, self.sendChannel, self.sendMode)
self.packetsSent = self.packetsSent + 1
self:resetSendSettings()
end
--- Add a callback to an event.
-- @tparam string event The event that will trigger the callback.
-- @tparam function callback The callback to be triggered.
-- @treturn function The callback that was passed in.
--@usage
--client:on("connect", function(data)
-- print("Connected to the server!")
--end)
function Client:on(event, callback)
return self.listener:addCallback(event, callback)
end
function Client:_activateTriggers(event, data)
local result = self.listener:trigger(event, data)
self.packetsReceived = self.packetsReceived + 1
if not result then
self:log("warning", "Tried to activate trigger: '" .. tostring(event) .. "' but it does not exist.")
end
end
--- Remove a specific callback for an event.
-- @tparam function callback The callback to remove.
-- @treturn boolean Whether or not the callback was removed.
--@usage
--local callback = client:on("chatMessage", function(message)
-- print(message)
--end)
--client:removeCallback(callback)
function Client:removeCallback(callback)
return self.listener:removeCallback(callback)
end
--- Log an event.
-- Alias for Client.logger:log.
-- @tparam string event The type of event that happened.
-- @tparam string data The message to log.
--@usage
--if somethingBadHappened then
-- client:log("error", "Something bad happened!")
--end
function Client:log(event, data)
return self.logger:log(event, data)
end
--- Reset all send options to their default values.
function Client:resetSendSettings()
self.sendMode = self.defaultSendMode
self.sendChannel = self.defaultSendChannel
end
--- Enables an adaptive order-2 PPM range coder for the transmitted data of all peers. Both the client and server must both either have compression enabled or disabled.
--
-- Note: lua-enet does not currently expose a way to disable the compression after it has been enabled.
function Client:enableCompression()
return self.host:compress_with_range_coder()
end
--- Set the send mode for the next outgoing message.
-- The mode will be reset after the next message is sent. The initial default
-- is "reliable".
-- @tparam string mode A valid send mode.
-- @see SEND_MODES
-- @usage
--client:setSendMode("unreliable")
--client:send("position", {...})
function Client:setSendMode(mode)
if not isValidSendMode(mode) then
self:log("warning", "Tried to use invalid send mode: '" .. mode .. "'. Defaulting to reliable.")
mode = "reliable"
end
self.sendMode = mode
end
--- Set the default send mode for all future outgoing messages.
-- The initial default is "reliable".
-- @tparam string mode A valid send mode.
-- @see SEND_MODES
function Client:setDefaultSendMode(mode)
if not isValidSendMode(mode) then
self:log("error", "Tried to set default send mode to invalid mode: '" .. mode .. "'")
error("Tried to set default send mode to invalid mode: '" .. mode .. "'")
end
self.defaultSendMode = mode
end
--- Set the send channel for the next outgoing message.
-- The channel will be reset after the next message. Channels are zero-indexed
-- and cannot exceed the maximum number of channels allocated. The initial
-- default is 0.
-- @tparam number channel Channel to send data on.
-- @usage
--client:setSendChannel(2) -- the third channel
--client:send("important", "The message")
function Client:setSendChannel(channel)
if channel > (self.maxChannels - 1) then
self:log("warning", "Tried to use invalid channel: " .. channel .. " (max is " .. self.maxChannels - 1 .. "). Defaulting to 0.")
channel = 0
end
self.sendChannel = channel
end
--- Set the default send channel for all future outgoing messages.
-- The initial default is 0.
-- @tparam number channel Channel to send data on.
function Client:setDefaultSendChannel(channel)
self.defaultSendChannel = channel
end
--- Set the data schema for an event.
--
-- Schemas allow you to set a specific format that the data will be sent. If the
-- client and server both know the format ahead of time, then the table keys
-- do not have to be sent across the network, which saves bandwidth.
-- @tparam string event The event to set the data schema for.
-- @tparam {string,...} schema The data schema.
-- @usage
-- server = sock.newServer(...)
-- client = sock.newClient(...)
--
-- -- Without schemas
-- server:send("update", {
-- x = 4,
-- y = 100,
-- vx = -4.5,
-- vy = 23.1,
-- rotation = 1.4365,
-- })
-- client:on("update", function(data)
-- -- data = {
-- -- x = 4,
-- -- y = 100,
-- -- vx = -4.5,
-- -- vy = 23.1,
-- -- rotation = 1.4365,
-- -- }
-- end)
--
--
-- -- With schemas
-- client:setSchema("update", {
-- "x",
-- "y",
-- "vx",
-- "vy",
-- "rotation",
-- })
-- -- client no longer has to send the keys, saving bandwidth
-- server:send("update", {
-- 4,
-- 100,
-- -4.5,
-- 23.1,
-- 1.4365,
-- })
-- client:on("update", function(data)
-- -- data = {
-- -- x = 4,
-- -- y = 100,
-- -- vx = -4.5,
-- -- vy = 23.1,
-- -- rotation = 1.4365,
-- -- }
-- end)