--------------------------------------------------------- --- UDP based messaging protocol with handshake to identify packets --------------------------------------------------------- local os = require('os') local math = require('math') local VERSION = "001" return function(ZD) ZD.ZDP = function(port, noDebug) local zdp = {} zdp.port = port zdp.peers = {} zdp.listener = {} zdp.debug = not noDebug zdp.on = function(zdp, packet, func) if not zdp.listener[packet] then zdp.listener[packet] = {} end table.insert(zdp.listener[packet], func) end zdp.call = function(zdp, packet, ...) if not zdp.listener[packet] then return end local rets = {} for k,v in pairs(zdp.listener[packet]) do if type(v) == "function" then local ret = v(...) if ret then table.insert(rets, ret) end end end return unpack(rets) end zdp.udp = ZD.UDP(zdp.port, function(client, msg) if not msg then return end if msg == "ZDP HANDSHAKE " .. VERSION then -- CHECK FOR SAME VERSION math.randomseed(os.time()) local id = msg .. client.address .. client.port .. os.time() .. math.random() -- GENERATE UNIQUE ID id = ZD.md5.sumhexa(id) local nid = ZD.md5.sumhexa(id) if zdp.debug then print("Received Handshake from", client.address, client.port) print("ID:", id) end client:send("ZDP HANDSHAKE " .. VERSION .. " /" .. id, function() client.lastHeartbeat = os.time() client.id = id client.nid = nid zdp.peers[id] = client zdp.call("authenticated", client) end) return end local packet = ZD.json:decode(msg) if type(packet) ~= "table" then return zdp.call("message", packet) end if not packet.id or not zdp.peers[packet.id] then return zdp.call("packet", packet) end if packet.name and packet.data then zdp.call(packet.name, zdp.peers[packet.id], packet.data) elseif packet.data then zdp.call("data", zdp.peers[packet.id], packet.data) end end) return zdp end end