2021-06-13 23:53:38 +03:00
|
|
|
import io
|
|
|
|
import net
|
|
|
|
|
|
|
|
// This file shows how a basic TCP echo server can be implemented using
|
|
|
|
// the net module. You can connect to the server by using netcat or telnet,
|
|
|
|
// in separate shells, for example:
|
|
|
|
// nc 127.0.0.1 12345
|
|
|
|
// or
|
|
|
|
// telnet 127.0.0.1 12345
|
|
|
|
|
|
|
|
fn main() {
|
2022-10-16 09:28:57 +03:00
|
|
|
mut server := net.listen_tcp(.ip6, ':12345')!
|
|
|
|
laddr := server.addr()!
|
2021-06-13 23:53:38 +03:00
|
|
|
eprintln('Listen on $laddr ...')
|
|
|
|
for {
|
2022-10-16 09:28:57 +03:00
|
|
|
mut socket := server.accept()!
|
2022-11-05 10:46:40 +03:00
|
|
|
spawn handle_client(mut socket)
|
2021-06-13 23:53:38 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn handle_client(mut socket net.TcpConn) {
|
|
|
|
defer {
|
|
|
|
socket.close() or { panic(err) }
|
|
|
|
}
|
|
|
|
client_addr := socket.peer_addr() or { return }
|
|
|
|
eprintln('> new client: $client_addr')
|
|
|
|
mut reader := io.new_buffered_reader(reader: socket)
|
|
|
|
defer {
|
2022-08-20 08:03:07 +03:00
|
|
|
unsafe {
|
|
|
|
reader.free()
|
|
|
|
}
|
2021-06-13 23:53:38 +03:00
|
|
|
}
|
|
|
|
socket.write_string('server: hello\n') or { return }
|
|
|
|
for {
|
|
|
|
received_line := reader.read_line() or { return }
|
|
|
|
if received_line == '' {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
println('client $client_addr: $received_line')
|
|
|
|
socket.write_string('server: $received_line\n') or { return }
|
|
|
|
}
|
|
|
|
}
|