SHARE
TWEET

Untitled

a guest Sep 24th, 2019 70 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. --- A Lua networking library for LÖVE games.
  2. -- * [Source code](https://github.com/camchenry/sock.lua)
  3. -- * [Examples](https://github.com/camchenry/sock.lua/tree/master/examples)
  4. -- @module sock
  5.  
  6. local sock = {
  7.     _VERSION     = 'sock.lua v0.3.0',
  8.     _DESCRIPTION = 'A Lua networking library for LÖVE games',
  9.     _URL         = 'https://github.com/camchenry/sock.lua',
  10.     _LICENSE     = [[
  11.         MIT License
  12.         Copyright (c) 2016 Cameron McHenry
  13.         Permission is hereby granted, free of charge, to any person obtaining a copy
  14.         of this software and associated documentation files (the "Software"), to deal
  15.         in the Software without restriction, including without limitation the rights
  16.         to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17.         copies of the Software, and to permit persons to whom the Software is
  18.         furnished to do so, subject to the following conditions:
  19.         The above copyright notice and this permission notice shall be included in all
  20.         copies or substantial portions of the Software.
  21.         THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22.         IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23.         FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24.         AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25.         LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26.         OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  27.         SOFTWARE.
  28.     ]]
  29. }
  30.  
  31. local enet = require "enet"
  32.  
  33. -- Current folder trick
  34. -- http://kiki.to/blog/2014/04/12/rule-5-beware-of-multiple-files/
  35. local currentFolder = (...):gsub('%.[^%.]+$', '')
  36.  
  37. local bitserLoaded = false
  38.  
  39. if bitser then
  40.     bitserLoaded = true
  41. end
  42.  
  43. -- Try to load some common serialization libraries
  44. -- This is for convenience, you may still specify your own serializer
  45. if not bitserLoaded then
  46.     bitserLoaded, bitser = pcall(require, "bitser")
  47. end
  48.  
  49. -- Try to load relatively
  50. if not bitserLoaded then
  51.     bitserLoaded, bitser = pcall(require, currentFolder .. ".bitser")
  52. end
  53.  
  54. -- links variables to keys based on their order
  55. -- note that it only works for boolean and number values, not strings
  56. local function zipTable(items, keys, event)
  57.     local data = {}
  58.  
  59.     -- convert variable at index 1 into the value for the key value at index 1, and so on
  60.     for i, value in ipairs(items) do
  61.         local key = keys[i]
  62.  
  63.         if not key then
  64.             error("Event '"..event.."' missing data key. Is the schema different between server and client?")
  65.         end
  66.  
  67.         data[key] = value
  68.     end
  69.  
  70.     return data
  71. end
  72.  
  73. --- All of the possible connection statuses for a client connection.
  74. -- @see Client:getState
  75. sock.CONNECTION_STATES = {
  76.     "disconnected",             -- Disconnected from the server.
  77.     "connecting",               -- In the process of connecting to the server.
  78.     "acknowledging_connect",    --
  79.     "connection_pending",       --
  80.     "connection_succeeded",     --
  81.     "connected",                -- Successfully connected to the server.
  82.     "disconnect_later",         -- Disconnecting, but only after sending all queued packets.
  83.     "disconnecting",            -- In the process of disconnecting from the server.
  84.     "acknowledging_disconnect", --
  85.     "zombie",                   --
  86.     "unknown",                  --
  87. }
  88.  
  89. --- States that represent the client connecting to a server.
  90. sock.CONNECTING_STATES = {
  91.     "connecting",               -- In the process of connecting to the server.
  92.     "acknowledging_connect",    --
  93.     "connection_pending",       --
  94.     "connection_succeeded",     --
  95. }
  96.  
  97. --- States that represent the client disconnecting from a server.
  98. sock.DISCONNECTING_STATES = {
  99.     "disconnect_later",         -- Disconnecting, but only after sending all queued packets.
  100.     "disconnecting",            -- In the process of disconnecting from the server.
  101.     "acknowledging_disconnect", --
  102. }
  103.  
  104. --- Valid modes for sending messages.
  105. sock.SEND_MODES = {
  106.     "reliable",     -- Message is guaranteed to arrive, and arrive in the order in which it is sent.
  107.     "unsequenced",  -- Message has no guarantee on the order that it arrives.
  108.     "unreliable",   -- Message is not guaranteed to arrive.
  109. }
  110.  
  111. local function isValidSendMode(mode)
  112.     for _, validMode in ipairs(sock.SEND_MODES) do
  113.         if mode == validMode then
  114.             return true
  115.         end
  116.     end
  117.     return false
  118. end
  119.  
  120. local Logger = {}
  121. local Logger_mt = {__index = Logger}
  122.  
  123. local function newLogger(source)
  124.     local logger = setmetatable({
  125.         source          = source,
  126.         messages        = {},
  127.  
  128.         -- Makes print info more concise, but should still log the full line
  129.         shortenLines    = true,
  130.         -- Print all incoming event data
  131.         printEventData  = false,
  132.         printErrors     = true,
  133.         printWarnings   = true,
  134.     }, Logger_mt)
  135.  
  136.     return logger
  137. end
  138.  
  139. function Logger:log(event, data)
  140.     local time = os.date("%X") -- something like 24:59:59
  141.     local shortLine = ("[%s] %s"):format(event, data)
  142.     local fullLine  = ("[%s][%s][%s] %s"):format(self.source, time, event, data)
  143.  
  144.     -- The printed message may or may not be the full message
  145.     local line = fullLine
  146.     if self.shortenLines then
  147.         line = shortLine
  148.     end
  149.  
  150.     if self.printEventData then
  151.         print(line)
  152.     elseif self.printErrors and event == "error" then
  153.         print(line)
  154.     elseif self.printWarnings and event == "warning" then
  155.         print(line)
  156.     end
  157.  
  158.     -- The logged message is always the full message
  159.     table.insert(self.messages, fullLine)
  160.  
  161.     -- TODO: Dump to a log file
  162. end
  163.  
  164. local Listener = {}
  165. local Listener_mt = {__index = Listener}
  166.  
  167. local function newListener()
  168.     local listener = setmetatable({
  169.         triggers        = {},
  170.         schemas         = {},
  171.     }, Listener_mt)
  172.  
  173.     return listener
  174. end
  175.  
  176. -- Adds a callback to a trigger
  177. -- Returns: the callback function
  178. function Listener:addCallback(event, callback)
  179.     if not self.triggers[event] then
  180.         self.triggers[event] = {}
  181.     end
  182.  
  183.     table.insert(self.triggers[event], callback)
  184.  
  185.     return callback
  186. end
  187.  
  188. -- Removes a callback on a given trigger
  189. -- Returns a boolean indicating if the callback was removed
  190. function Listener:removeCallback(callback)
  191.     for _, triggers in pairs(self.triggers) do
  192.         for i, trigger in pairs(triggers) do
  193.             if trigger == callback then
  194.                 table.remove(triggers, i)
  195.                 return true
  196.             end
  197.         end
  198.     end
  199.     return false
  200. end
  201.  
  202. -- Accepts: event (string), schema (table)
  203. -- Returns: nothing
  204. function Listener:setSchema(event, schema)
  205.     self.schemas[event] = schema
  206. end
  207.  
  208. -- Activates all callbacks for a trigger
  209. -- Returns a boolean indicating if any callbacks were triggered
  210. function Listener:trigger(event, data, client)
  211.     if self.triggers[event] then
  212.         for _, trigger in pairs(self.triggers[event]) do
  213.             -- Event has a pre-existing schema defined
  214.             if self.schemas[event] then
  215.                 data = zipTable(data, self.schemas[event], event)
  216.             end
  217.             trigger(data, client)
  218.         end
  219.         return true
  220.     else
  221.         return false
  222.     end
  223. end
  224.  
  225. --- Manages all clients and receives network events.
  226. -- @type Server
  227. local Server = {}
  228. local Server_mt = {__index = Server}
  229.  
  230. --- Check for network events and handle them.
  231. function Server:update()
  232.     local event = self.host:service(self.messageTimeout)
  233.  
  234.     while event do
  235.         if event.type == "connect" then
  236.             local eventClient = sock.newClient(event.peer)
  237.             eventClient:setSerialization(self.serialize, self.deserialize)
  238.             table.insert(self.peers, event.peer)
  239.             table.insert(self.clients, eventClient)
  240.             self:_activateTriggers("connect", event.data, eventClient)
  241.             self:log(event.type, tostring(event.peer) .. " connected")
  242.  
  243.         elseif event.type == "receive" then
  244.             local eventName, data = self:__unpack(event.data)
  245.             local eventClient = self:getClient(event.peer)
  246.  
  247.             self:_activateTriggers(eventName, data, eventClient)
  248.             self:log(eventName, data)
  249.  
  250.         elseif event.type == "disconnect" then
  251.             -- remove from the active peer list
  252.             for i, peer in pairs(self.peers) do
  253.                 if peer == event.peer then
  254.                     table.remove(self.peers, i)
  255.                 end
  256.             end
  257.             local eventClient = self:getClient(event.peer)
  258.             for i, client in pairs(self.clients) do
  259.                 if client == eventClient then
  260.                     table.remove(self.clients, i)
  261.                 end
  262.             end
  263.             self:_activateTriggers("disconnect", event.data, eventClient)
  264.             self:log(event.type, tostring(event.peer) .. " disconnected")
  265.  
  266.         end
  267.  
  268.         event = self.host:service(self.messageTimeout)
  269.     end
  270. end
  271.  
  272. -- Creates the unserialized message that will be used in callbacks
  273. -- In: serialized message (string)
  274. -- Out: event (string), data (mixed)
  275. function Server:__unpack(data)
  276.     if not self.deserialize then
  277.         self:log("error", "Can't deserialize message: deserialize was not set")
  278.         error("Can't deserialize message: deserialize was not set")
  279.     end
  280.  
  281.     local message = self.deserialize(data)
  282.     local eventName, data = message[1], message[2]
  283.     return eventName, data
  284. end
  285.  
  286. -- Creates the serialized message that will be sent over the network
  287. -- In: event (string), data (mixed)
  288. -- Out: serialized message (string)
  289. function Server:__pack(event, data)
  290.     local message = {event, data}
  291.     local serializedMessage
  292.  
  293.     if not self.serialize then
  294.         self:log("error", "Can't serialize message: serialize was not set")
  295.         error("Can't serialize message: serialize was not set")
  296.     end
  297.  
  298.     -- 'Data' = binary data class in Love
  299.     if type(data) == "userdata" and data.type and data:typeOf("Data") then
  300.         message[2] = data:getString()
  301.         serializedMessage = self.serialize(message)
  302.     else
  303.         serializedMessage = self.serialize(message)
  304.     end
  305.  
  306.     return serializedMessage
  307. end
  308.  
  309. --- Send a message to all clients, except one.
  310. -- Useful for when the client does something locally, but other clients
  311. -- need to be updated at the same time. This way avoids duplicating objects by
  312. -- never sending its own event to itself in the first place.
  313. -- @tparam Client client The client to not receive the message.
  314. -- @tparam string event The event to trigger with this message.
  315. -- @param data The data to send.
  316. function Server:sendToAllBut(client, event, data)
  317.     local serializedMessage = self:__pack(event, data)
  318.  
  319.     for _, p in pairs(self.peers) do
  320.         if p ~= client.connection then
  321.             self.packetsSent = self.packetsSent + 1
  322.             p:send(serializedMessage, self.sendChannel, self.sendMode)
  323.         end
  324.     end
  325.  
  326.     self:resetSendSettings()
  327. end
  328.  
  329. --- Send a message to all clients.
  330. -- @tparam string event The event to trigger with this message.
  331. -- @param data The data to send.
  332. --@usage
  333. --server:sendToAll("gameStarting", true)
  334. function Server:sendToAll(event, data)
  335.     local serializedMessage = self:__pack(event, data)
  336.  
  337.     self.packetsSent = self.packetsSent + #self.peers
  338.  
  339.     self.host:broadcast(serializedMessage, self.sendChannel, self.sendMode)
  340.  
  341.     self:resetSendSettings()
  342. end
  343.  
  344. --- Send a message to a single peer. Useful to send data to a newly connected player
  345. -- without sending to everyone who already received it.
  346. -- @tparam enet_peer peer The enet peer to receive the message.
  347. -- @tparam string event The event to trigger with this message.
  348. -- @param data data to send to the peer.
  349. --@usage
  350. --server:sendToPeer(peer, "initialGameInfo", {...})
  351. function Server:sendToPeer(peer, event, data)
  352.     local serializedMessage = self:__pack(event, data)
  353.  
  354.     self.packetsSent = self.packetsSent + 1
  355.  
  356.     peer:send(serializedMessage, self.sendChannel, self.sendMode)
  357.  
  358.     self:resetSendSettings()
  359. end
  360.  
  361. --- Add a callback to an event.
  362. -- @tparam string event The event that will trigger the callback.
  363. -- @tparam function callback The callback to be triggered.
  364. -- @treturn function The callback that was passed in.
  365. --@usage
  366. --server:on("connect", function(data, client)
  367. --    print("Client connected!")
  368. --end)
  369. function Server:on(event, callback)
  370.     return self.listener:addCallback(event, callback)
  371. end
  372.  
  373. function Server:_activateTriggers(event, data, client)
  374.     local result = self.listener:trigger(event, data, client)
  375.  
  376.     self.packetsReceived = self.packetsReceived + 1
  377.  
  378.     if not result then
  379.         self:log("warning", "Tried to activate trigger: '" .. tostring(event) .. "' but it does not exist.")
  380.     end
  381. end
  382.  
  383. --- Remove a specific callback for an event.
  384. -- @tparam function callback The callback to remove.
  385. -- @treturn boolean Whether or not the callback was removed.
  386. --@usage
  387. --local callback = server:on("chatMessage", function(message)
  388. --    print(message)
  389. --end)
  390. --server:removeCallback(callback)
  391. function Server:removeCallback(callback)
  392.     return self.listener:removeCallback(callback)
  393. end
  394.  
  395. --- Log an event.
  396. -- Alias for Server.logger:log.
  397. -- @tparam string event The type of event that happened.
  398. -- @tparam string data The message to log.
  399. --@usage
  400. --if somethingBadHappened then
  401. --    server:log("error", "Something bad happened!")
  402. --end
  403. function Server:log(event, data)
  404.     return self.logger:log(event, data)
  405. end
  406.  
  407. --- Reset all send options to their default values.
  408. function Server:resetSendSettings()
  409.     self.sendMode = self.defaultSendMode
  410.     self.sendChannel = self.defaultSendChannel
  411. end
  412.  
  413. --- 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.
  414. --
  415. -- Note: lua-enet does not currently expose a way to disable the compression after it has been enabled.
  416. function Server:enableCompression()
  417.     return self.host:compress_with_range_coder()
  418. end
  419.  
  420. --- Destroys the server and frees the port it is bound to.
  421. function Server:destroy()
  422.     self.host:destroy()
  423. end
  424.  
  425. --- Set the send mode for the next outgoing message.
  426. -- The mode will be reset after the next message is sent. The initial default
  427. -- is "reliable".
  428. -- @tparam string mode A valid send mode.
  429. -- @see SEND_MODES
  430. -- @usage
  431. --server:setSendMode("unreliable")
  432. --server:sendToAll("playerState", {...})
  433. function Server:setSendMode(mode)
  434.     if not isValidSendMode(mode) then
  435.         self:log("warning", "Tried to use invalid send mode: '" .. mode .. "'. Defaulting to reliable.")
  436.         mode = "reliable"
  437.     end
  438.  
  439.     self.sendMode = mode
  440. end
  441.  
  442. --- Set the default send mode for all future outgoing messages.
  443. -- The initial default is "reliable".
  444. -- @tparam string mode A valid send mode.
  445. -- @see SEND_MODES
  446. function Server:setDefaultSendMode(mode)
  447.     if not isValidSendMode(mode) then
  448.         self:log("error", "Tried to set default send mode to invalid mode: '" .. mode .. "'")
  449.         error("Tried to set default send mode to invalid mode: '" .. mode .. "'")
  450.     end
  451.  
  452.     self.defaultSendMode = mode
  453. end
  454.  
  455. --- Set the send channel for the next outgoing message.
  456. -- The channel will be reset after the next message. Channels are zero-indexed
  457. -- and cannot exceed the maximum number of channels allocated. The initial
  458. -- default is 0.
  459. -- @tparam number channel Channel to send data on.
  460. -- @usage
  461. --server:setSendChannel(2) -- the third channel
  462. --server:sendToAll("importantEvent", "The message")
  463. function Server:setSendChannel(channel)
  464.     if channel > (self.maxChannels - 1) then
  465.         self:log("warning", "Tried to use invalid channel: " .. channel .. " (max is " .. self.maxChannels - 1 .. "). Defaulting to 0.")
  466.         channel = 0
  467.     end
  468.  
  469.     self.sendChannel = channel
  470. end
  471.  
  472. --- Set the default send channel for all future outgoing messages.
  473. -- The initial default is 0.
  474. -- @tparam number channel Channel to send data on.
  475. function Server:setDefaultSendChannel(channel)
  476.    self.defaultSendChannel = channel
  477. end
  478.  
  479. --- Set the data schema for an event.
  480. --
  481. -- Schemas allow you to set a specific format that the data will be sent. If the
  482. -- client and server both know the format ahead of time, then the table keys
  483. -- do not have to be sent across the network, which saves bandwidth.
  484. -- @tparam string event The event to set the data schema for.
  485. -- @tparam {string,...} schema The data schema.
  486. -- @usage
  487. -- server = sock.newServer(...)
  488. -- client = sock.newClient(...)
  489. --
  490. -- -- Without schemas
  491. -- client:send("update", {
  492. --     x = 4,
  493. --     y = 100,
  494. --     vx = -4.5,
  495. --     vy = 23.1,
  496. --     rotation = 1.4365,
  497. -- })
  498. -- server:on("update", function(data, client)
  499. --     -- data = {
  500. --     --    x = 4,
  501. --     --    y = 100,
  502. --     --    vx = -4.5,
  503. --     --    vy = 23.1,
  504. --     --    rotation = 1.4365,
  505. --     -- }
  506. -- end)
  507. --
  508. --
  509. -- -- With schemas
  510. -- server:setSchema("update", {
  511. --     "x",
  512. --     "y",
  513. --     "vx",
  514. --     "vy",
  515. --     "rotation",
  516. -- })
  517. -- -- client no longer has to send the keys, saving bandwidth
  518. -- client:send("update", {
  519. --     4,
  520. --     100,
  521. --     -4.5,
  522. --     23.1,
  523. --     1.4365,
  524. -- })
  525. -- server:on("update", function(data, client)
  526. --     -- data = {
  527. --     --    x = 4,
  528. --     --    y = 100,
  529. --     --    vx = -4.5,
  530. --     --    vy = 23.1,
  531. --     --    rotation = 1.4365,
  532. --     -- }
  533. -- end)
  534. function Server:setSchema(event, schema)
  535.     return self.listener:setSchema(event, schema)
  536. end
  537.  
  538. --- Set the incoming and outgoing bandwidth limits.
  539. -- @tparam number incoming The maximum incoming bandwidth in bytes.
  540. -- @tparam number outgoing The maximum outgoing bandwidth in bytes.
  541. function Server:setBandwidthLimit(incoming, outgoing)
  542.     return self.host:bandwidth_limit(incoming, outgoing)
  543. end
  544.  
  545. --- Set the maximum number of channels.
  546. -- @tparam number limit The maximum number of channels allowed. If it is 0,
  547. -- then the maximum number of channels available on the system will be used.
  548. function Server:setMaxChannels(limit)
  549.     self.host:channel_limit(limit)
  550. end
  551.  
  552. --- Set the timeout to wait for packets.
  553. -- @tparam number timeout Time to wait for incoming packets in milliseconds. The
  554. -- initial default is 0.
  555. function Server:setMessageTimeout(timeout)
  556.     self.messageTimeout = timeout
  557. end
  558.  
  559. --- Set the serialization functions for sending and receiving data.
  560. -- Both the client and server must share the same serialization method.
  561. -- @tparam function serialize The serialization function to use.
  562. -- @tparam function deserialize The deserialization function to use.
  563. -- @usage
  564. --bitser = require "bitser" -- or any library you like
  565. --server = sock.newServer("localhost", 22122)
  566. --server:setSerialization(bitser.dumps, bitser.loads)
  567. function Server:setSerialization(serialize, deserialize)
  568.     assert(type(serialize) == "function", "Serialize must be a function, got: '"..type(serialize).."'")
  569.     assert(type(deserialize) == "function", "Deserialize must be a function, got: '"..type(deserialize).."'")
  570.     self.serialize = serialize
  571.     self.deserialize = deserialize
  572. end
  573.  
  574. --- Gets the Client object associated with an enet peer.
  575. -- @tparam peer peer An enet peer.
  576. -- @treturn Client Object associated with the peer.
  577. function Server:getClient(peer)
  578.     for _, client in pairs(self.clients) do
  579.         if peer == client.connection then
  580.             return client
  581.         end
  582.     end
  583. end
  584.  
  585. --- Gets the Client object that has the given connection id.
  586. -- @tparam number connectId The unique client connection id.
  587. -- @treturn Client
  588. function Server:getClientByConnectId(connectId)
  589.     for _, client in pairs(self.clients) do
  590.         if connectId == client.connectId then
  591.             return client
  592.         end
  593.     end
  594. end
  595.  
  596. --- Get the Client object that has the given peer index.
  597. -- @treturn Client
  598. function Server:getClientByIndex(index)
  599.     for _, client in pairs(self.clients) do
  600.         if index == client:getIndex() then
  601.             return client
  602.         end
  603.     end
  604. end
  605.  
  606. --- Get the enet_peer that has the given index.
  607. -- @treturn enet_peer The underlying enet peer object.
  608. function Server:getPeerByIndex(index)
  609.     return self.host:get_peer(index)
  610. end
  611.  
  612. --- Get the total sent data since the server was created.
  613. -- @treturn number The total sent data in bytes.
  614. function Server:getTotalSentData()
  615.     return self.host:total_sent_data()
  616. end
  617.  
  618. --- Get the total received data since the server was created.
  619. -- @treturn number The total received data in bytes.
  620. function Server:getTotalReceivedData()
  621.     return self.host:total_received_data()
  622. end
  623. --- Get the total number of packets (messages) sent since the server was created.
  624. -- Everytime a message is sent or received, the corresponding figure is incremented.
  625. -- Therefore, this is not necessarily an accurate indicator of how many packets were actually
  626. -- exchanged over the network.
  627. -- @treturn number The total number of sent packets.
  628. function Server:getTotalSentPackets()
  629.     return self.packetsSent
  630. end
  631.  
  632. --- Get the total number of packets (messages) received since the server was created.
  633. -- @treturn number The total number of received packets.
  634. -- @see Server:getTotalSentPackets
  635. function Server:getTotalReceivedPackets()
  636.     return self.packetsReceived
  637. end
  638.  
  639. --- Get the last time when network events were serviced.
  640. -- @treturn number Timestamp of the last time events were serviced.
  641. function Server:getLastServiceTime()
  642.     return self.host:service_time()
  643. end
  644.  
  645. --- Get the number of allocated slots for peers.
  646. -- @treturn number Number of allocated slots.
  647. function Server:getMaxPeers()
  648.     return self.maxPeers
  649. end
  650.  
  651. --- Get the number of allocated channels.
  652. -- Channels are zero-indexed, e.g. 16 channels allocated means that the
  653. -- maximum channel that can be used is 15.
  654. -- @treturn number Number of allocated channels.
  655. function Server:getMaxChannels()
  656.     return self.maxChannels
  657. end
  658.  
  659. --- Get the timeout for packets.
  660. -- @treturn number Time to wait for incoming packets in milliseconds.
  661. -- initial default is 0.
  662. function Server:getMessageTimeout()
  663.     return self.messageTimeout
  664. end
  665.  
  666. --- Get the socket address of the host.
  667. -- @treturn string A description of the socket address, in the format
  668. -- "A.B.C.D:port" where A.B.C.D is the IP address of the used socket.
  669. function Server:getSocketAddress()
  670.     return self.host:get_socket_address()
  671. end
  672.  
  673. --- Get the current send mode.
  674. -- @treturn string
  675. -- @see SEND_MODES
  676. function Server:getSendMode()
  677.     return self.sendMode
  678. end
  679.  
  680. --- Get the default send mode.
  681. -- @treturn string
  682. -- @see SEND_MODES
  683. function Server:getDefaultSendMode()
  684.     return self.defaultSendMode
  685. end
  686.  
  687. --- Get the IP address or hostname that the server was created with.
  688. -- @treturn string
  689. function Server:getAddress()
  690.     return self.address
  691. end
  692.  
  693. --- Get the port that the server is hosted on.
  694. -- @treturn number
  695. function Server:getPort()
  696.     return self.port
  697. end
  698.  
  699. --- Get the table of Clients actively connected to the server.
  700. -- @return {Client,...}
  701. function Server:getClients()
  702.     return self.clients
  703. end
  704.  
  705. --- Get the number of Clients that are currently connected to the server.
  706. -- @treturn number The number of active clients.
  707. function Server:getClientCount()
  708.     return #self.clients
  709. end
  710.  
  711.  
  712. --- Connects to servers.
  713. -- @type Client
  714. local Client = {}
  715. local Client_mt = {__index = Client}
  716.  
  717. --- Check for network events and handle them.
  718. function Client:update()
  719.     local event = self.host:service(self.messageTimeout)
  720.  
  721.     while event do
  722.         if event.type == "connect" then
  723.             self:_activateTriggers("connect", event.data)
  724.             self:log(event.type, "Connected to " .. tostring(self.connection))
  725.         elseif event.type == "receive" then
  726.             local eventName, data = self:__unpack(event.data)
  727.  
  728.             self:_activateTriggers(eventName, data)
  729.             self:log(eventName, data)
  730.  
  731.         elseif event.type == "disconnect" then
  732.             self:_activateTriggers("disconnect", event.data)
  733.             self:log(event.type, "Disconnected from " .. tostring(self.connection))
  734.         end
  735.  
  736.         event = self.host:service(self.messageTimeout)
  737.     end
  738. end
  739.  
  740. --- Connect to the chosen server.
  741. -- Connection will not actually occur until the next time `Client:update` is called.
  742. -- @tparam ?number code A number that can be associated with the connect event.
  743. function Client:connect(code)
  744.     -- number of channels for the client and server must match
  745.     self.connection = self.host:connect(self.address .. ":" .. self.port, self.maxChannels, code)
  746.     self.connectId = self.connection:connect_id()
  747. end
  748.  
  749. --- Disconnect from the server, if connected. The client will disconnect the
  750. -- next time that network messages are sent.
  751. -- @tparam ?number code A code to associate with this disconnect event.
  752. -- @todo Pass the code into the disconnect callback on the server
  753. function Client:disconnect(code)
  754.     code = code or 0
  755.     self.connection:disconnect(code)
  756. end
  757.  
  758. --- Disconnect from the server, if connected. The client will disconnect after
  759. -- sending all queued packets.
  760. -- @tparam ?number code A code to associate with this disconnect event.
  761. -- @todo Pass the code into the disconnect callback on the server
  762. function Client:disconnectLater(code)
  763.     code = code or 0
  764.     self.connection:disconnect_later(code)
  765. end
  766.  
  767. --- Disconnect from the server, if connected. The client will disconnect immediately.
  768. -- @tparam ?number code A code to associate with this disconnect event.
  769. -- @todo Pass the code into the disconnect callback on the server
  770. function Client:disconnectNow(code)
  771.     code = code or 0
  772.     self.connection:disconnect_now(code)
  773. end
  774.  
  775. --- Forcefully disconnects the client. The server is not notified of the disconnection.
  776. -- @tparam Client client The client to reset.
  777. function Client:reset()
  778.     if self.connection then
  779.         self.connection:reset()
  780.     end
  781. end
  782.  
  783. -- Creates the unserialized message that will be used in callbacks
  784. -- In: serialized message (string)
  785. -- Out: event (string), data (mixed)
  786. function Client:__unpack(data)
  787.     if not self.deserialize then
  788.         self:log("error", "Can't deserialize message: deserialize was not set")
  789.         error("Can't deserialize message: deserialize was not set")
  790.     end
  791.  
  792.     local message = self.deserialize(data)
  793.     local eventName, data = message[1], message[2]
  794.     return eventName, data
  795. end
  796.  
  797. -- Creates the serialized message that will be sent over the network
  798. -- In: event (string), data (mixed)
  799. -- Out: serialized message (string)
  800. function Client:__pack(event, data)
  801.     local message = {event, data}
  802.     local serializedMessage
  803.  
  804.     if not self.serialize then
  805.         self:log("error", "Can't serialize message: serialize was not set")
  806.         error("Can't serialize message: serialize was not set")
  807.     end
  808.  
  809.     -- 'Data' = binary data class in Love
  810.     if type(data) == "userdata" and data.type and data:typeOf("Data") then
  811.         message[2] = data:getString()
  812.         serializedMessage = self.serialize(message)
  813.     else
  814.         serializedMessage = self.serialize(message)
  815.     end
  816.  
  817.     return serializedMessage
  818. end
  819.  
  820. --- Send a message to the server.
  821. -- @tparam string event The event to trigger with this message.
  822. -- @param data The data to send.
  823. function Client:send(event, data)
  824.     local serializedMessage = self:__pack(event, data)
  825.  
  826.     self.connection:send(serializedMessage, self.sendChannel, self.sendMode)
  827.  
  828.     self.packetsSent = self.packetsSent + 1
  829.  
  830.     self:resetSendSettings()
  831. end
  832.  
  833. --- Add a callback to an event.
  834. -- @tparam string event The event that will trigger the callback.
  835. -- @tparam function callback The callback to be triggered.
  836. -- @treturn function The callback that was passed in.
  837. --@usage
  838. --client:on("connect", function(data)
  839. --    print("Connected to the server!")
  840. --end)
  841. function Client:on(event, callback)
  842.     return self.listener:addCallback(event, callback)
  843. end
  844.  
  845. function Client:_activateTriggers(event, data)
  846.     local result = self.listener:trigger(event, data)
  847.  
  848.     self.packetsReceived = self.packetsReceived + 1
  849.  
  850.     if not result then
  851.         self:log("warning", "Tried to activate trigger: '" .. tostring(event) .. "' but it does not exist.")
  852.     end
  853. end
  854.  
  855. --- Remove a specific callback for an event.
  856. -- @tparam function callback The callback to remove.
  857. -- @treturn boolean Whether or not the callback was removed.
  858. --@usage
  859. --local callback = client:on("chatMessage", function(message)
  860. --    print(message)
  861. --end)
  862. --client:removeCallback(callback)
  863. function Client:removeCallback(callback)
  864.     return self.listener:removeCallback(callback)
  865. end
  866.  
  867. --- Log an event.
  868. -- Alias for Client.logger:log.
  869. -- @tparam string event The type of event that happened.
  870. -- @tparam string data The message to log.
  871. --@usage
  872. --if somethingBadHappened then
  873. --    client:log("error", "Something bad happened!")
  874. --end
  875. function Client:log(event, data)
  876.     return self.logger:log(event, data)
  877. end
  878.  
  879. --- Reset all send options to their default values.
  880. function Client:resetSendSettings()
  881.     self.sendMode = self.defaultSendMode
  882.     self.sendChannel = self.defaultSendChannel
  883. end
  884.  
  885. --- 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.
  886. --
  887. -- Note: lua-enet does not currently expose a way to disable the compression after it has been enabled.
  888. function Client:enableCompression()
  889.     return self.host:compress_with_range_coder()
  890. end
  891.  
  892. --- Set the send mode for the next outgoing message.
  893. -- The mode will be reset after the next message is sent. The initial default
  894. -- is "reliable".
  895. -- @tparam string mode A valid send mode.
  896. -- @see SEND_MODES
  897. -- @usage
  898. --client:setSendMode("unreliable")
  899. --client:send("position", {...})
  900. function Client:setSendMode(mode)
  901.     if not isValidSendMode(mode) then
  902.         self:log("warning", "Tried to use invalid send mode: '" .. mode .. "'. Defaulting to reliable.")
  903.         mode = "reliable"
  904.     end
  905.  
  906.     self.sendMode = mode
  907. end
  908.  
  909. --- Set the default send mode for all future outgoing messages.
  910. -- The initial default is "reliable".
  911. -- @tparam string mode A valid send mode.
  912. -- @see SEND_MODES
  913. function Client:setDefaultSendMode(mode)
  914.     if not isValidSendMode(mode) then
  915.         self:log("error", "Tried to set default send mode to invalid mode: '" .. mode .. "'")
  916.         error("Tried to set default send mode to invalid mode: '" .. mode .. "'")
  917.     end
  918.  
  919.     self.defaultSendMode = mode
  920. end
  921.  
  922. --- Set the send channel for the next outgoing message.
  923. -- The channel will be reset after the next message. Channels are zero-indexed
  924. -- and cannot exceed the maximum number of channels allocated. The initial
  925. -- default is 0.
  926. -- @tparam number channel Channel to send data on.
  927. -- @usage
  928. --client:setSendChannel(2) -- the third channel
  929. --client:send("important", "The message")
  930. function Client:setSendChannel(channel)
  931.     if channel > (self.maxChannels - 1) then
  932.         self:log("warning", "Tried to use invalid channel: " .. channel .. " (max is " .. self.maxChannels - 1 .. "). Defaulting to 0.")
  933.         channel = 0
  934.     end
  935.  
  936.     self.sendChannel = channel
  937. end
  938.  
  939. --- Set the default send channel for all future outgoing messages.
  940. -- The initial default is 0.
  941. -- @tparam number channel Channel to send data on.
  942. function Client:setDefaultSendChannel(channel)
  943.     self.defaultSendChannel = channel
  944. end
  945.  
  946. --- Set the data schema for an event.
  947. --
  948. -- Schemas allow you to set a specific format that the data will be sent. If the
  949. -- client and server both know the format ahead of time, then the table keys
  950. -- do not have to be sent across the network, which saves bandwidth.
  951. -- @tparam string event The event to set the data schema for.
  952. -- @tparam {string,...} schema The data schema.
  953. -- @usage
  954. -- server = sock.newServer(...)
  955. -- client = sock.newClient(...)
  956. --
  957. -- -- Without schemas
  958. -- server:send("update", {
  959. --     x = 4,
  960. --     y = 100,
  961. --     vx = -4.5,
  962. --     vy = 23.1,
  963. --     rotation = 1.4365,
  964. -- })
  965. -- client:on("update", function(data)
  966. --     -- data = {
  967. --     --    x = 4,
  968. --     --    y = 100,
  969. --     --    vx = -4.5,
  970. --     --    vy = 23.1,
  971. --     --    rotation = 1.4365,
  972. --     -- }
  973. -- end)
  974. --
  975. --
  976. -- -- With schemas
  977. -- client:setSchema("update", {
  978. --     "x",
  979. --     "y",
  980. --     "vx",
  981. --     "vy",
  982. --     "rotation",
  983. -- })
  984. -- -- client no longer has to send the keys, saving bandwidth
  985. -- server:send("update", {
  986. --     4,
  987. --     100,
  988. --     -4.5,
  989. --     23.1,
  990. --     1.4365,
  991. -- })
  992. -- client:on("update", function(data)
  993. --     -- data = {
  994. --     --    x = 4,
  995. --     --    y = 100,
  996. --     --    vx = -4.5,
  997. --     --    vy = 23.1,
  998. --     --    rotation = 1.4365,
  999. --     -- }
  1000. -- end)
  1001. function Client:setSchema(event, schema)
  1002.     return self.listener:setSchema(event, schema)
  1003. end
  1004.  
  1005. --- Set the maximum number of channels.
  1006. -- @tparam number limit The maximum number of channels allowed. If it is 0,
  1007. -- then the maximum number of channels available on the system will be used.
  1008. function Client:setMaxChannels(limit)
  1009.     self.host:channel_limit(limit)
  1010. end
  1011.  
  1012. --- Set the timeout to wait for packets.
  1013. -- @tparam number timeout Time to wait for incoming packets in milliseconds. The initial
  1014. -- default is 0.
  1015. function Client:setMessageTimeout(timeout)
  1016.     self.messageTimeout = timeout
  1017. end
  1018.  
  1019. --- Set the incoming and outgoing bandwidth limits.
  1020. -- @tparam number incoming The maximum incoming bandwidth in bytes.
  1021. -- @tparam number outgoing The maximum outgoing bandwidth in bytes.
  1022. function Client:setBandwidthLimit(incoming, outgoing)
  1023.     return self.host:bandwidth_limit(incoming, outgoing)
  1024. end
  1025.  
  1026. --- Set how frequently to ping the server.
  1027. -- The round trip time is updated each time a ping is sent. The initial
  1028. -- default is 500ms.
  1029. -- @tparam number interval The interval, in milliseconds.
  1030. function Client:setPingInterval(interval)
  1031.     if self.connection then
  1032.         self.connection:ping_interval(interval)
  1033.     end
  1034. end
  1035.  
  1036. --- Change the probability at which unreliable packets should not be dropped.
  1037. -- @tparam number interval Interval, in milliseconds, over which to measure lowest mean RTT. (default: 5000ms)
  1038. -- @tparam number acceleration Rate at which to increase the throttle probability as mean RTT declines. (default: 2)
  1039. -- @tparam number deceleration Rate at which to decrease the throttle probability as mean RTT increases.
  1040. function Client:setThrottle(interval, acceleration, deceleration)
  1041.     interval = interval or 5000
  1042.     acceleration = acceleration or 2
  1043.     deceleration = deceleration or 2
  1044.     if self.connection then
  1045.         self.connection:throttle_configure(interval, acceleration, deceleration)
  1046.     end
  1047. end
  1048.  
  1049. --- Set the parameters for attempting to reconnect if a timeout is detected.
  1050. -- @tparam ?number limit A factor that is multiplied with a value that based on the average round trip time to compute the timeout limit. (default: 32)
  1051. -- @tparam ?number minimum Timeout value in milliseconds that a reliable packet has to be acknowledged if the variable timeout limit was exceeded. (default: 5000)
  1052. -- @tparam ?number maximum Fixed timeout in milliseconds for which any packet has to be acknowledged.
  1053. function Client:setTimeout(limit, minimum, maximum)
  1054.     limit = limit or 32
  1055.     minimum = minimum or 5000
  1056.     maximum = maximum or 30000
  1057.     if self.connection then
  1058.         self.connection:timeout(limit, minimum, maximum)
  1059.     end
  1060. end
  1061.  
  1062. --- Set the serialization functions for sending and receiving data.
  1063. -- Both the client and server must share the same serialization method.
  1064. -- @tparam function serialize The serialization function to use.
  1065. -- @tparam function deserialize The deserialization function to use.
  1066. -- @usage
  1067. --bitser = require "bitser" -- or any library you like
  1068. --client = sock.newClient("localhost", 22122)
  1069. --client:setSerialization(bitser.dumps, bitser.loads)
  1070. function Client:setSerialization(serialize, deserialize)
  1071.     assert(type(serialize) == "function", "Serialize must be a function, got: '"..type(serialize).."'")
  1072.     assert(type(deserialize) == "function", "Deserialize must be a function, got: '"..type(deserialize).."'")
  1073.     self.serialize = serialize
  1074.     self.deserialize = deserialize
  1075. end
  1076.  
  1077. --- Gets whether the client is connected to the server.
  1078. -- @treturn boolean Whether the client is connected to the server.
  1079. -- @usage
  1080. -- client:connect()
  1081. -- client:isConnected() -- false
  1082. -- -- After a few client updates
  1083. -- client:isConnected() -- true
  1084. function Client:isConnected()
  1085.     return self.connection ~= nil and self:getState() == "connected"
  1086. end
  1087.  
  1088. --- Gets whether the client is disconnected from the server.
  1089. -- @treturn boolean Whether the client is connected to the server.
  1090. -- @usage
  1091. -- client:disconnect()
  1092. -- client:isDisconnected() -- false
  1093. -- -- After a few client updates
  1094. -- client:isDisconnected() -- true
  1095. function Client:isDisconnected()
  1096.     return self.connection ~= nil and self:getState() == "disconnected"
  1097. end
  1098.  
  1099. --- Gets whether the client is connecting to the server.
  1100. -- @treturn boolean Whether the client is connected to the server.
  1101. -- @usage
  1102. -- client:connect()
  1103. -- client:isConnecting() -- true
  1104. -- -- After a few client updates
  1105. -- client:isConnecting() -- false
  1106. -- client:isConnected() -- true
  1107. function Client:isConnecting()
  1108.     local inConnectingState = false
  1109.     for _, state in ipairs(sock.CONNECTING_STATES) do
  1110.         if state == self:getState() then
  1111.             inConnectingState = true
  1112.             break
  1113.         end
  1114.     end
  1115.     return self.connection ~= nil and inConnectingState
  1116. end
  1117.  
  1118. --- Gets whether the client is disconnecting from the server.
  1119. -- @treturn boolean Whether the client is connected to the server.
  1120. -- @usage
  1121. -- client:disconnect()
  1122. -- client:isDisconnecting() -- true
  1123. -- -- After a few client updates
  1124. -- client:isDisconnecting() -- false
  1125. -- client:isDisconnected() -- true
  1126. function Client:isDisconnecting()
  1127.     local inDisconnectingState = false
  1128.     for _, state in ipairs(sock.DISCONNECTING_STATES) do
  1129.         if state == self:getState() then
  1130.             inDisconnectingState = true
  1131.             break
  1132.         end
  1133.     end
  1134.     return self.connection ~= nil and inDisconnectingState
  1135. end
  1136.  
  1137. --- Get the total sent data since the server was created.
  1138. -- @treturn number The total sent data in bytes.
  1139. function Client:getTotalSentData()
  1140.     return self.host:total_sent_data()
  1141. end
  1142.  
  1143. --- Get the total received data since the server was created.
  1144. -- @treturn number The total received data in bytes.
  1145. function Client:getTotalReceivedData()
  1146.     return self.host:total_received_data()
  1147. end
  1148.  
  1149. --- Get the total number of packets (messages) sent since the client was created.
  1150. -- Everytime a message is sent or received, the corresponding figure is incremented.
  1151. -- Therefore, this is not necessarily an accurate indicator of how many packets were actually
  1152. -- exchanged over the network.
  1153. -- @treturn number The total number of sent packets.
  1154. function Client:getTotalSentPackets()
  1155.     return self.packetsSent
  1156. end
  1157.  
  1158. --- Get the total number of packets (messages) received since the client was created.
  1159. -- @treturn number The total number of received packets.
  1160. -- @see Client:getTotalSentPackets
  1161. function Client:getTotalReceivedPackets()
  1162.     return self.packetsReceived
  1163. end
  1164.  
  1165. --- Get the last time when network events were serviced.
  1166. -- @treturn number Timestamp of the last time events were serviced.
  1167. function Client:getLastServiceTime()
  1168.     return self.host:service_time()
  1169. end
  1170.  
  1171. --- Get the number of allocated channels.
  1172. -- Channels are zero-indexed, e.g. 16 channels allocated means that the
  1173. -- maximum channel that can be used is 15.
  1174. -- @treturn number Number of allocated channels.
  1175. function Client:getMaxChannels()
  1176.     return self.maxChannels
  1177. end
  1178.  
  1179. --- Get the timeout for packets.
  1180. -- @treturn number Time to wait for incoming packets in milliseconds.
  1181. -- initial default is 0.
  1182. function Client:getMessageTimeout()
  1183.     return self.messageTimeout
  1184. end
  1185.  
  1186. --- Return the round trip time (RTT, or ping) to the server, if connected.
  1187. -- It can take a few seconds for the time to approach an accurate value.
  1188. -- @treturn number The round trip time.
  1189. function Client:getRoundTripTime()
  1190.     if self.connection then
  1191.         return self.connection:round_trip_time()
  1192.     end
  1193. end
  1194.  
  1195. --- Get the unique connection id, if connected.
  1196. -- @treturn number The connection id.
  1197. function Client:getConnectId()
  1198.     if self.connection then
  1199.         return self.connection:connect_id()
  1200.     end
  1201. end
  1202.  
  1203. --- Get the current connection state, if connected.
  1204. -- @treturn string The connection state.
  1205. -- @see CONNECTION_STATES
  1206. function Client:getState()
  1207.     if self.connection then
  1208.         return self.connection:state()
  1209.     end
  1210. end
  1211.  
  1212. --- Get the index of the enet peer. All peers of an ENet host are kept in an array. This function finds and returns the index of the peer of its host structure.
  1213. -- @treturn number The index of the peer.
  1214. function Client:getIndex()
  1215.     if self.connection then
  1216.         return self.connection:index()
  1217.     end
  1218. end
  1219.  
  1220. --- Get the socket address of the host.
  1221. -- @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.
  1222. function Client:getSocketAddress()
  1223.     return self.host:get_socket_address()
  1224. end
  1225.  
  1226. --- Get the enet_peer that has the given index.
  1227. -- @treturn enet_peer The underlying enet peer object.
  1228. function Client:getPeerByIndex(index)
  1229.     return self.host:get_peer(index)
  1230. end
  1231.  
  1232. --- Get the current send mode.
  1233. -- @treturn string
  1234. -- @see SEND_MODES
  1235. function Client:getSendMode()
  1236.     return self.sendMode
  1237. end
  1238.  
  1239. --- Get the default send mode.
  1240. -- @treturn string
  1241. -- @see SEND_MODES
  1242. function Client:getDefaultSendMode()
  1243.     return self.defaultSendMode
  1244. end
  1245.  
  1246. --- Get the IP address or hostname that the client was created with.
  1247. -- @treturn string
  1248. function Client:getAddress()
  1249.     return self.address
  1250. end
  1251.  
  1252. --- Get the port that the client is connecting to.
  1253. -- @treturn number
  1254. function Client:getPort()
  1255.     return self.port
  1256. end
  1257.  
  1258. --- Creates a new Server object.
  1259. -- @tparam ?string address Hostname or IP address to bind to. (default: "localhost")
  1260. -- @tparam ?number port Port to listen to for data. (default: 22122)
  1261. -- @tparam ?number maxPeers Maximum peers that can connect to the server. (default: 64)
  1262. -- @tparam ?number maxChannels Maximum channels available to send and receive data. (default: 1)
  1263. -- @tparam ?number inBandwidth Maximum incoming bandwidth (default: 0)
  1264. -- @tparam ?number outBandwidth Maximum outgoing bandwidth (default: 0)
  1265. -- @return A new Server object.
  1266. -- @see Server
  1267. -- @within sock
  1268. -- @usage
  1269. --local sock = require "sock"
  1270. --
  1271. -- -- Local server hosted on localhost:22122 (by default)
  1272. --server = sock.newServer()
  1273. --
  1274. -- -- Local server only, on port 1234
  1275. --server = sock.newServer("localhost", 1234)
  1276. --
  1277. -- -- Server hosted on static IP 123.45.67.89, on port 22122
  1278. --server = sock.newServer("123.45.67.89", 22122)
  1279. --
  1280. -- -- Server hosted on any IP, on port 22122
  1281. --server = sock.newServer("*", 22122)
  1282. --
  1283. -- -- Limit peers to 10, channels to 2
  1284. --server = sock.newServer("*", 22122, 10, 2)
  1285. --
  1286. -- -- Limit incoming/outgoing bandwidth to 1kB/s (1000 bytes/s)
  1287. --server = sock.newServer("*", 22122, 10, 2, 1000, 1000)
  1288. sock.newServer = function(address, port, maxPeers, maxChannels, inBandwidth, outBandwidth)
  1289.     address         = address or "localhost"
  1290.     port            = port or 22122
  1291.     maxPeers        = maxPeers or 64
  1292.     maxChannels     = maxChannels or 1
  1293.     inBandwidth     = inBandwidth or 0
  1294.     outBandwidth    = outBandwidth or 0
  1295.  
  1296.     local server = setmetatable({
  1297.         address         = address,
  1298.         port            = port,
  1299.         host            = nil,
  1300.  
  1301.         messageTimeout  = 0,
  1302.         maxChannels     = maxChannels,
  1303.         maxPeers        = maxPeers,
  1304.         sendMode        = "reliable",
  1305.         defaultSendMode = "reliable",
  1306.         sendChannel     = 0,
  1307.         defaultSendChannel = 0,
  1308.  
  1309.         peers           = {},
  1310.         clients         = {},
  1311.  
  1312.         listener        = newListener(),
  1313.         logger          = newLogger("SERVER"),
  1314.  
  1315.         serialize       = nil,
  1316.         deserialize     = nil,
  1317.  
  1318.         packetsSent     = 0,
  1319.         packetsReceived = 0,
  1320.     }, Server_mt)
  1321.  
  1322.     -- ip, max peers, max channels, in bandwidth, out bandwidth
  1323.     -- number of channels for the client and server must match
  1324.     server.host = enet.host_create(server.address .. ":" .. server.port, server.maxPeers, server.maxChannels)
  1325.  
  1326.     if not server.host then
  1327.         error("Failed to create the host. Is there another server running on :"..server.port.."?")
  1328.     end
  1329.  
  1330.     server:setBandwidthLimit(inBandwidth, outBandwidth)
  1331.  
  1332.     if bitserLoaded then
  1333.         server:setSerialization(bitser.dumps, bitser.loads)
  1334.     end
  1335.  
  1336.     return server
  1337. end
  1338.  
  1339. --- Creates a new Client instance.
  1340. -- @tparam ?string/peer serverOrAddress Usually the IP address or hostname to connect to. It can also be an enet peer. (default: "localhost")
  1341. -- @tparam ?number port Port number of the server to connect to. (default: 22122)
  1342. -- @tparam ?number maxChannels Maximum channels available to send and receive data. (default: 1)
  1343. -- @return A new Client object.
  1344. -- @see Client
  1345. -- @within sock
  1346. -- @usage
  1347. --local sock = require "sock"
  1348. --
  1349. -- -- Client that will connect to localhost:22122 (by default)
  1350. --client = sock.newClient()
  1351. --
  1352. -- -- Client that will connect to localhost:1234
  1353. --client = sock.newClient("localhost", 1234)
  1354. --
  1355. -- -- Client that will connect to 123.45.67.89:1234, using two channels
  1356. -- -- NOTE: Server must also allocate two channels!
  1357. --client = sock.newClient("123.45.67.89", 1234, 2)
  1358. sock.newClient = function(serverOrAddress, port, maxChannels)
  1359.     serverOrAddress = serverOrAddress or "localhost"
  1360.     port            = port or 22122
  1361.     maxChannels     = maxChannels or 1
  1362.  
  1363.     local client = setmetatable({
  1364.         address         = nil,
  1365.         port            = nil,
  1366.         host            = nil,
  1367.  
  1368.         connection      = nil,
  1369.         connectId       = nil,
  1370.  
  1371.         messageTimeout  = 0,
  1372.         maxChannels     = maxChannels,
  1373.         sendMode        = "reliable",
  1374.         defaultSendMode = "reliable",
  1375.         sendChannel     = 0,
  1376.         defaultSendChannel = 0,
  1377.  
  1378.         listener        = newListener(),
  1379.         logger          = newLogger("CLIENT"),
  1380.  
  1381.         serialize       = nil,
  1382.         deserialize     = nil,
  1383.  
  1384.         packetsReceived = 0,
  1385.         packetsSent     = 0,
  1386.     }, Client_mt)
  1387.  
  1388.     -- Two different forms for client creation:
  1389.     -- 1. Pass in (address, port) and connect to that.
  1390.     -- 2. Pass in (enet peer) and set that as the existing connection.
  1391.     -- The first would be the common usage for regular client code, while the
  1392.     -- latter is mostly used for creating clients in the server-side code.
  1393.  
  1394.     -- First form: (address, port)
  1395.     if port ~= nil and type(port) == "number" and serverOrAddress ~= nil and type(serverOrAddress) == "string" then
  1396.         client.address = serverOrAddress
  1397.         client.port = port
  1398.         client.host = enet.host_create()
  1399.  
  1400.     -- Second form: (enet peer)
  1401.     elseif type(serverOrAddress) == "userdata" then
  1402.         client.connection = serverOrAddress
  1403.         client.connectId = client.connection:connect_id()
  1404.     end
  1405.  
  1406.     if bitserLoaded then
  1407.         client:setSerialization(bitser.dumps, bitser.loads)
  1408.     end
  1409.  
  1410.     return client
  1411. end
  1412.  
  1413. return sock
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top