v / examples
Raw file
		
1import io
2import net
3
4// This file shows how a basic TCP echo server can be implemented using
5// the net module. You can connect to the server by using netcat or telnet,
6// in separate shells, for example:
7// nc 127.0.0.1 12345
8// or
9// telnet 127.0.0.1 12345
10
11fn main() {
12 mut server := net.listen_tcp(.ip6, ':12345')?
13 laddr := server.addr()?
14 eprintln('Listen on $laddr ...')
15 for {
16 mut socket := server.accept()?
17 go handle_client(mut socket)
18 }
19}
20
21fn handle_client(mut socket net.TcpConn) {
22 defer {
23 socket.close() or { panic(err) }
24 }
25 client_addr := socket.peer_addr() or { return }
26 eprintln('> new client: $client_addr')
27 mut reader := io.new_buffered_reader(reader: socket)
28 defer {
29 unsafe {
30 reader.free()
31 }
32 }
33 socket.write_string('server: hello\n') or { return }
34 for {
35 received_line := reader.read_line() or { return }
36 if received_line == '' {
37 return
38 }
39 println('client $client_addr: $received_line')
40 socket.write_string('server: $received_line\n') or { return }
41 }
42}