add a base64 implementation (based on FreeBSD code)
[project/libubox.git] / examples / uloop-example.lua
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
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
22 uloop.timer(function() print("2000 ms timer run"); end, 2000)
23
24 -- timer example 3
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 udp_ev = uloop.fd_add(udp, function(ufd, events)
50         local words, msg_or_ip, port_or_nil = ufd:receivefrom()
51         print('Recv UDP packet from '..msg_or_ip..':'..port_or_nil..' : '..words)
52         if words == "Stop!" then
53                 udp_ev:delete()
54         end
55 end, uloop.ULOOP_READ)
56
57 udp_count = 0
58 udp_send_timer = uloop.timer(
59         function()
60                 local s = socket.udp()
61                 local words
62                 if udp_count > 3 then
63                         words = "Stop!"
64                         udp_send_timer:cancel()
65                 else
66                         words = 'Hello!'
67                         udp_send_timer:set(1000)
68                 end
69                 print('Send UDP packet to 127.0.0.1:8080 :'..words)
70                 s:sendto(words, '127.0.0.1', 8080)
71                 s:close()
72
73                 udp_count = udp_count + 1
74         end, 3000
75 )
76
77 uloop.run()
78