uloop-example.lua 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #!/usr/bin/env lua
  2. local socket = require "socket"
  3. local uloop = require("uloop")
  4. uloop.init()
  5. local udp = socket.udp()
  6. udp:settimeout(0)
  7. udp:setsockname('*', 8080)
  8. -- timer example 1
  9. local timer
  10. function t()
  11. print("1000 ms timer run");
  12. timer:set(1000)
  13. end
  14. timer = uloop.timer(t)
  15. timer:set(1000)
  16. -- timer example 2
  17. uloop.timer(function() print("2000 ms timer run"); end, 2000)
  18. -- timer example 3
  19. uloop.timer(function() print("3000 ms timer run"); end, 3000):cancel()
  20. -- process
  21. function p1(r)
  22. print("Process 1 completed")
  23. print(r)
  24. end
  25. function p2(r)
  26. print("Process 2 completed")
  27. print(r)
  28. end
  29. uloop.timer(
  30. function()
  31. uloop.process("uloop_pid_test.sh", {"foo", "bar"}, {"PROCESS=1"}, p1)
  32. end, 1000
  33. )
  34. uloop.timer(
  35. function()
  36. uloop.process("uloop_pid_test.sh", {"foo", "bar"}, {"PROCESS=2"}, p2)
  37. end, 2000
  38. )
  39. udp_ev = uloop.fd_add(udp, function(ufd, events)
  40. local words, msg_or_ip, port_or_nil = ufd:receivefrom()
  41. print('Recv UDP packet from '..msg_or_ip..':'..port_or_nil..' : '..words)
  42. if words == "Stop!" then
  43. udp_ev:delete()
  44. end
  45. end, uloop.ULOOP_READ)
  46. udp_count = 0
  47. udp_send_timer = uloop.timer(
  48. function()
  49. local s = socket.udp()
  50. local words
  51. if udp_count > 3 then
  52. words = "Stop!"
  53. udp_send_timer:cancel()
  54. else
  55. words = 'Hello!'
  56. udp_send_timer:set(1000)
  57. end
  58. print('Send UDP packet to 127.0.0.1:8080 :'..words)
  59. s:sendto(words, '127.0.0.1', 8080)
  60. s:close()
  61. udp_count = udp_count + 1
  62. end, 3000
  63. )
  64. uloop.run()