v / examples
Raw file
		
1import os
2import os.cmdline
3import net
4
5fn main() {
6 println('Usage: net_udp_server_and_client [-l] [-p 5000]')
7 println(' -l - act as a server and listen')
8 println(' -p XXXX - custom port number')
9 println('------------------------------------------')
10 is_server := '-l' in os.args
11 port := cmdline.option(os.args, '-p', '40001').int()
12 mut buf := []u8{len: 100}
13 if is_server {
14 println('UDP echo server, listening for udp packets on port: $port')
15 mut c := net.listen_udp(':$port')?
16 for {
17 read, addr := c.read(mut buf) or { continue }
18 println('received $read bytes from $addr')
19 c.write_to(addr, buf[..read]) or {
20 println('Server: connection dropped')
21 continue
22 }
23 }
24 } else {
25 println('UDP client, sending packets to port: ${port}.\nType `exit` to exit.')
26 mut c := net.dial_udp('localhost:$port')?
27 for {
28 mut line := os.input('client > ')
29 match line {
30 '' {
31 line = '\n'
32 }
33 'exit' {
34 println('goodbye.')
35 exit(0)
36 }
37 else {}
38 }
39 c.write_string(line)?
40 read, _ := c.read(mut buf)?
41 println('server : ' + buf[0..read].bytestr())
42 }
43 }
44}