Advertisement
Snusmumriken

udprint

Feb 26th, 2024
653
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.12 KB | None | 0 0
  1. local socket = require'socket'
  2.  
  3. local function gettime()
  4.     local time = socket.gettime()
  5.     local msec = time - math.floor(time)
  6.     local date = os.date("%d.%m.%y-%X", time)
  7.     return ("%-21s"):format(date .. "." .. math.floor(msec * 300))
  8. end
  9.  
  10. local function server(host, port)
  11.     host = host or "*"
  12.     port = port or 4096
  13.     local udp = (socket.udp4 or socket.udp)()
  14.     assert(udp:setsockname(host, port))
  15.     --udp:listen()
  16.    
  17.     return function()
  18.         local msg, host, port = udp:receivefrom()
  19.         print(gettime() .. " " .. host .. ":" .. port .. " > " .. msg)
  20.     end, udp:getsockname()
  21. end
  22.  
  23. local function client(host, port)
  24.     host = host or "127.0.0.1"
  25.     port = port or 4096
  26.     local udp = (socket.udp4 or socket.udp)()
  27.    
  28.     return function(...)
  29.         local msg = ""
  30.         for i = 1, select("#", ...) do
  31.             msg = msg .. "\t" .. tostring(select(i, ...))
  32.         end
  33.         udp:sendto(msg, host, port)
  34.     end
  35. end
  36.  
  37. if ... then
  38.     return {
  39.         server = server,
  40.         client = client
  41.     }
  42. end
  43.  
  44. local server, host, port = server()
  45. host = socket.dns.toip("")
  46. print("Listen ", host, port)
  47.  
  48. while 1 do
  49.     server()
  50. end
  51.  
  52. -- print = require'udprint'.client("host_ip")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement