v / vlib / net / tcp_test.v
91 lines · 79 sloc · 2.04 KB · 4db6408e0b94d7adb55a5aaf0e362e1e1b408e0b
Raw
1// vtest flaky: true
2// vtest retry: 5
3import net
4
5const test_port = 45123
6
7fn handle_conn(mut c net.TcpConn) {
8 for {
9 mut buf := []u8{len: 100, init: 0}
10 read := c.read(mut buf) or {
11 println('Server: connection dropped')
12 return
13 }
14 c.write(buf[..read]) or {
15 println('Server: connection dropped')
16 return
17 }
18 }
19}
20
21fn one_shot_echo_server(mut l net.TcpListener, ch_started chan int) ! {
22 eprintln('> one_shot_echo_server')
23 ch_started <- 1
24 mut new_conn := l.accept() or { return error('could not accept') }
25 eprintln(' > new_conn: ${new_conn}')
26 handle_conn(mut new_conn)
27 new_conn.close() or {}
28}
29
30fn echo(address string) ! {
31 mut c := net.dial_tcp(address)!
32 defer {
33 c.close() or {}
34 }
35
36 println('local: ' + c.addr()!.str())
37 println(' peer: ' + c.peer_addr()!.str())
38 ip := c.peer_ip()!
39 println(' ip: ${ip}')
40 assert ip in ['::1', 'localhost', '127.0.0.1']
41
42 data := 'Hello from vlib/net!'
43 c.write_string(data)!
44 mut buf := []u8{len: 4096}
45 read := c.read(mut buf) or { panic(err) }
46 assert read == data.len
47 for i := 0; i < read; i++ {
48 assert buf[i] == data[i]
49 }
50 println('Got "${buf.bytestr()}"')
51}
52
53fn test_tcp_ip6() {
54 eprintln('\n>>> ${@FN}')
55 address := 'localhost:${test_port}'
56 mut l := net.listen_tcp(.ip6, ':${test_port}') or { panic(err) }
57 dump(l)
58 start_echo_server(mut l)
59 echo(address) or { panic(err) }
60 l.close() or {}
61 // ensure there is at least one new socket created before the next test
62 l = net.listen_tcp(.ip6, ':${test_port + 1}') or { panic(err) }
63}
64
65fn start_echo_server(mut l net.TcpListener) {
66 ch_server_started := chan int{}
67 spawn one_shot_echo_server(mut l, ch_server_started)
68 _ := <-ch_server_started
69}
70
71fn test_tcp_ip() {
72 eprintln('\n>>> ${@FN}')
73 address := 'localhost:${test_port}'
74 mut l := net.listen_tcp(.ip, address) or { panic(err) }
75 dump(l)
76 start_echo_server(mut l)
77 echo(address) or { panic(err) }
78 l.close() or {}
79}
80
81fn test_tcp_unix() {
82 eprintln('\n>>> ${@FN}')
83 address := 'tcp-test.sock'
84
85 mut l := net.listen_tcp(.unix, address) or { return }
86 assert false
87}
88
89fn testsuite_end() {
90 eprintln('\ndone')
91}
92