1 #!/usr/bin/env lua 2 3 local socket = require "socket" 4 5 local uloop = require("uloop") 6 uloop.init() 7 8 local udp = socket.udp() 9 udp:settimeout(0) 10 udp:setsockname('*', 8080) 11 12 -- timer example 1 (will run repeatedly) 13 local timer 14 function t() 15 print("1000 ms timer run"); 16 timer:set(1000) 17 end 18 timer = uloop.timer(t) 19 timer:set(1000) 20 21 -- timer example 2 (will run once) 22 uloop.timer(function() print("2000 ms timer run"); end, 2000) 23 24 -- timer example 3 (will never run) 25 uloop.timer(function() print("3000 ms timer run"); end, 3000):cancel() 26 27 -- process 28 function p1(r) 29 print("Process 1 completed") 30 print(r) 31 end 32 33 function p2(r) 34 print("Process 2 completed") 35 print(r) 36 end 37 38 uloop.timer( 39 function() 40 uloop.process("uloop_pid_test.sh", {"foo", "bar"}, {"PROCESS=1"}, p1) 41 end, 1000 42 ) 43 uloop.timer( 44 function() 45 uloop.process("uloop_pid_test.sh", {"foo", "bar"}, {"PROCESS=2"}, p2) 46 end, 2000 47 ) 48 49 -- Keep udp_ev reference, events will be gc'd, even if the callback is still referenced 50 -- .delete will manually untrack. 51 udp_ev = uloop.fd_add(udp, function(ufd, events) 52 local words, msg_or_ip, port_or_nil = ufd:receivefrom() 53 print('Recv UDP packet from '..msg_or_ip..':'..port_or_nil..' : '..words) 54 if words == "Stop!" then 55 udp_ev:delete() 56 end 57 end, uloop.ULOOP_READ) 58 59 udp_count = 0 60 udp_send_timer = uloop.timer( 61 function() 62 local s = socket.udp() 63 local words 64 if udp_count > 3 then 65 words = "Stop!" 66 udp_send_timer:cancel() 67 else 68 words = 'Hello!' 69 udp_send_timer:set(1000) 70 end 71 print('Send UDP packet to 127.0.0.1:8080 :'..words) 72 s:sendto(words, '127.0.0.1', 8080) 73 s:close() 74 75 udp_count = udp_count + 1 76 end, 3000 77 ) 78 79 uloop.run() 80
This page was automatically generated by LXR 0.3.1. • OpenWrt