Landin library reference discuss source

compiler/tests/fixtures/runtime/network-echo/main.ldn

1--  Echo over loopback: a server and its client in one program, over TCP
2--  and over UDP, on IPv4's loopback address and on IPv6's.  The server
3--  reads the client's lines through a line reader and writes them back
4--  through a buffered writer, the client reads them back through a line
5--  reader of its own, and the report goes to standard output through a
6--  buffered writer, flushed on every way out.
7import core/failure
8import core/io
9import core/net
10import core/text
11import core/time
12import hosted/blocking
13
14--- What the client sends over TCP: three lines.
15request: []u8 = "one\ntwo\nhello, world\n"
16
17--- What the client sends over UDP: two datagrams.
18messages: [2][]u8 = ["ping", "hello, datagram"]
19
20--- A reply came from somewhere other than the server it was sent to.
21wrong_sender: atom
22
23--- Serve `connection`: read each line through a line reader and write it
24--- back through a buffered writer, until the client has finished sending,
25--- and then finish sending too.  `lines` is how many it echoed.
26serve: (provider: type is net.network, host: provider, connection: io.file)
27       -> (lines: usize) ! ... =
28    mut incoming: [64]u8 = zeroed
29    mut reader := io.lines_over(host, connection, incoming)
30    mut outgoing: [64]u8 = zeroed
31    mut writer := io.buffered_over(host, connection, outgoing)
32    lines = 0
33    loop do
34        item: io.line = try io.read_line(reader)
35        break when item.at_end
36        try io.put(writer, item.bytes)
37        try io.put(writer, "\n")
38        inc lines
39    end loop
40    try io.flush(writer)
41    try net.shutdown(host, connection, net.sending)
42end serve
43
44--- Echo `request` over TCP between a server and a client on `family`'s
45--- loopback address, and put what the client read back in `echoed`, a line
46--- at a time; `lines` is how many the server echoed.  The listener asks for
47--- port 0, any free one, and says which it got; the client sends all of
48--- its lines and finishes sending before the server accepts, which the
49--- system's buffers allow in one thread.
50tcp_echo: (provider: type is net.network, host: provider,
51           family: net.address_family, inout echoed: text.builder)
52          -> (lines: usize) ! ... =
53    listener: io.file = try net.listen(host, net.loopback(family, 0))
54    defer net.close(host, listener) else none
55    at: net.address = try net.local_address(host, listener)
56    client: io.file = try net.connect(host, at)
57    defer net.close(host, client) else none
58    try net.set_timeouts(host, client, time.seconds(5), time.seconds(5))
59    try net.send(host, client, request)
60    try net.shutdown(host, client, net.sending)
61    server: io.file = try net.accept(host, listener)
62    defer net.close(host, server) else none
63    try net.set_timeouts(host, server, time.seconds(5), time.seconds(5))
64    lines = try serve(host, server)
65    mut incoming: [64]u8 = zeroed
66    mut replies := io.lines_over(host, client, incoming)
67    loop do
68        item: io.line = try io.read_line(replies)
69        break when item.at_end
70        try text.append(echoed, item.bytes)
71        try text.append_byte(echoed, u8('\n'))
72    end loop
73end tcp_echo
74
75--- Echo `messages` over UDP between two sockets on `family`'s loopback
76--- address: the server sends each datagram back to whoever sent it, and
77--- the client puts each reply in `echoed`, a line each.
78udp_echo: (provider: type is net.network, host: provider,
79           family: net.address_family, inout echoed: text.builder)
80          -> none ! ... =
81    server: io.file = try net.open_datagram(host, net.loopback(family, 0))
82    defer net.close(host, server) else none
83    client: io.file = try net.open_datagram(host, net.loopback(family, 0))
84    defer net.close(host, client) else none
85    try net.set_timeouts(host, server, time.seconds(5), time.seconds(5))
86    try net.set_timeouts(host, client, time.seconds(5), time.seconds(5))
87    at: net.address = try net.local_address(host, server)
88    mut buffer: [64]u8 = zeroed
89    for message in messages do
90        try net.send_to(host, client, message, at)
91        got: net.datagram = try net.receive_from(host, server, buffer)
92        try net.send_to(host, server, buffer[0..<got.count], got.sender)
93        back: net.datagram = try net.receive_from(host, client, buffer)
94        fail wrong_sender when not net.same_address(back.sender, at)
95        try text.append(echoed, buffer[0..<back.count])
96        try text.append_byte(echoed, u8('\n'))
97    end for
98end udp_echo
99
100--- Write each line of `bytes` to `out` after a bar.
101quoted: (provider: type is io.writer, inout out: io.buffered_writer(provider),
102         bytes: []u8) -> none ! ... =
103    mut start: usize = 0
104    for at in usize(0)..<lenof bytes do
105        if bytes[at] == 10 then
106            try io.put(out, "| ")
107            try io.put(out, bytes[start..<at + 1])
108            start = at + 1
109        end if
110    end for
111end quoted
112
113--- Report what came back over `protocol` on `family`'s loopback address:
114--- `count` of `what` the server echoed, and each of them.
115report: (provider: type is io.writer, inout out: io.buffered_writer(provider),
116         protocol: []u8, family: net.address_family, count: usize,
117         what: []u8, echoed: []u8) -> none ! ... =
118    mut room: [64]u8 = zeroed
119    mut line := text.over(room)
120    at: net.address = net.loopback(family, 0)
121    try text.append(line, protocol)
122    try text.append(line, " over ")
123    try net.append_ip(line, at)
124    try text.format(line, ": the server echoed {} {}\n",
125                    [any(addr count), any(addr what)])
126    try io.put(out, text.used(line))
127    try quoted(out, echoed)
128end report
129
130--- Echo over TCP and then UDP on `family`'s loopback address, and report
131--- what came back to `out`.
132exchange: (host: blocking.host,
133           inout out: io.buffered_writer(blocking.host),
134           family: net.address_family) -> none ! ... =
135    mut room: [256]u8 = zeroed
136    mut echoed := text.over(room)
137    lines: usize = try tcp_echo(host, family, echoed)
138    try report(out, "TCP", family, lines, "lines", text.used(echoed))
139    text.clear(echoed)
140    try udp_echo(host, family, echoed)
141    try report(out, "UDP", family, lenof messages, "datagrams",
142               text.used(echoed))
143end exchange
144
145--- Say on standard error why the echo could not be run or reported.
146complain: (host: blocking.host, problem: wrong_sender | failure.reason)
147          -> none =
148    reason: []u8 = match problem
149        wrong_sender: "a datagram came from the wrong sender"
150        _ (rest): failure.words(rest)
151    end match
152    io.write(host, io.err(host), "echo: ") else none
153    io.write(host, io.err(host), reason) else none
154    io.write(host, io.err(host), "\n") else none
155end complain
156
157public main: () -> (code: i32) =
158    host := blocking.new()
159    mut storage: [512]u8 = zeroed
160    mut out := io.buffered_over(host, io.out(host), storage)
161    defer io.flush(out) else none
162    code = 1
163    families: [2]net.address_family = [net.ipv4, net.ipv6]
164    for family in families do
165        exchange(host, out, family) else (problem)
166            --  A system without IPv6 cannot run the second half, which
167            --  says so rather than passing over it.
168            if problem == net.address_unavailable then
169                io.put(out, "this system has no such loopback address\n")
170                    else none
171                code = 2
172            else
173                complain(host, problem)
174            end if
175            return
176        end
177    end for
178    io.flush(out) else (problem)
179        complain(host, problem)
180        return
181    end
182    code = 0
183end main