1 | import net |
2 | import time |
3 | |
4 | fn echo_server(mut c net.UdpConn) { |
5 | mut count := 0 |
6 | for { |
7 | eprintln('> echo_server loop count: ${count}') |
8 | mut buf := []u8{len: 100} |
9 | read, addr := c.read(mut buf) or { continue } |
10 | eprintln('Server got addr ${addr}, read: ${read} | buf: ${buf}') |
11 | c.write_to(addr, buf[..read]) or { |
12 | println('Server: connection dropped') |
13 | return |
14 | } |
15 | count++ |
16 | // Normally, after responding, the test will end, but there are sometimes cases, |
17 | // when the echo_server continued looping, printing messages constantly. |
18 | // The sleep here, is a small precaution against spamming the CI with log messages, |
19 | // when there are network problems, and it allows easier root cause diagnostic, when |
20 | // they do happen: |
21 | time.sleep(1000 * time.millisecond) |
22 | } |
23 | } |
24 | |
25 | const server_addr = '127.0.0.1:40003' |
26 | |
27 | fn echo() ! { |
28 | mut c := net.dial_udp(server_addr) or { panic('could not net.dial_udp: ${err}') } |
29 | defer { |
30 | c.close() or {} |
31 | } |
32 | data := 'Hello from vlib/net!' |
33 | |
34 | c.write_string(data) or { panic('could not write_string: ${err}') } |
35 | |
36 | mut buf := []u8{len: 100, init: 0} |
37 | read, addr := c.read(mut buf) or { panic('could not read: ${err}') } |
38 | |
39 | assert read == data.len |
40 | println('Got address ${addr}') |
41 | // Can't test this here because loopback addresses |
42 | // are mapped to other addresses |
43 | // assert addr.str() == '127.0.0.1:30001' |
44 | |
45 | for i := 0; i < read; i++ { |
46 | assert buf[i] == data[i] |
47 | } |
48 | |
49 | println('Got "${buf.bytestr()}"') |
50 | |
51 | c.close()! |
52 | } |
53 | |
54 | fn test_udp() { |
55 | mut l := net.listen_udp(server_addr) or { panic('could not listen_udp: ${err}') } |
56 | |
57 | spawn echo_server(mut l) |
58 | echo() or { panic('could not echo: ${err}') } |
59 | |
60 | l.close() or {} |
61 | } |