echosrvr.lua 836 B

12345678910111213141516171819202122232425262728
  1. -----------------------------------------------------------------------------
  2. -- UDP sample: echo protocol server
  3. -- LuaSocket sample files
  4. -- Author: Diego Nehab
  5. -----------------------------------------------------------------------------
  6. local socket = require("socket")
  7. host = host or "127.0.0.1"
  8. port = port or 7
  9. if arg then
  10. host = arg[1] or host
  11. port = arg[2] or port
  12. end
  13. print("Binding to host '" ..host.. "' and port " ..port.. "...")
  14. udp = assert(socket.udp())
  15. assert(udp:setsockname(host, port))
  16. assert(udp:settimeout(5))
  17. ip, port = udp:getsockname()
  18. assert(ip, port)
  19. print("Waiting packets on " .. ip .. ":" .. port .. "...")
  20. while 1 do
  21. dgram, ip, port = udp:receivefrom()
  22. if dgram then
  23. print("Echoing '" .. dgram .. "' to " .. ip .. ":" .. port)
  24. udp:sendto(dgram, ip, port)
  25. else
  26. print(ip)
  27. end
  28. end