1#!./parrot
2# Copyright (C) 2011, Parrot Foundation.
3
4=head1 NAME
5
6t/pmc/testlib/test_server_ipv6.pir - Test server for the Socket PMC (IPv6 version)
7
8=head1 DESCRIPTION
9
10This server process is launched from t/pmc/socket.t to test the Socket PMC.
11
12It listens on localhost:1234 and accepts only one connection. It echoes
13everything it reads from that connection back to the client.
14
15Upon successful startup the string "Server started" is printed to stdout.
16
17After a timeout of 3 seconds, the process exits so it doesn't wait forever
18in case of test failures.
19
20=cut
21
22.include 'socket.pasm'
23
24.sub main :main
25    .local pmc sock, address, conn
26    .local string str
27    .local int len, status, port
28
29    sock = new 'Socket'
30    sock.'socket'(.PIO_PF_INET6, .PIO_SOCK_STREAM, .PIO_PROTO_TCP)
31    port = 1234
32    push_eh error
33  retry:
34    address = sock.'getaddrinfo'('::1', port, .PIO_PROTO_TCP, .PIO_PF_INET6, 1)
35    sock.'bind'(address)
36    goto started
37  error:
38    inc port
39    if port < 1244 goto retry
40    pop_eh
41    say "couldn't bind to a free port, exiting"
42    exit 1
43
44  started:
45    pop_eh
46    sock.'listen'(5)
47    print 'Server started, listening on port '
48    say port
49
50    status = sock.'poll'(1, 3, 0)
51    # timeout
52    if status == 0 goto conn_done
53    conn = sock.'accept'()
54    str = conn.'local_address'()
55
56    print 'Connection from '
57    say str
58
59    # echo incoming data
60  recv_loop:
61    status = conn.'poll'(1, 3, 0)
62    # timeout
63    if status == 0 goto recv_done
64    str = conn.'recv'()
65    len = length str
66    if len == 0 goto recv_done
67    conn.'send'(str)
68    goto recv_loop
69
70  recv_done:
71    conn.'close'()
72  conn_done:
73    sock.'close'()
74.end
75
76# Local Variables:
77#   mode: pir
78#   fill-column: 100
79# End:
80# vim: expandtab shiftwidth=4 ft=pir:
81
82