2020-03-28 10:21:22 +01:00
|
|
|
import net
|
2020-07-04 13:10:48 +02:00
|
|
|
|
2020-03-28 10:21:22 +01:00
|
|
|
// 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`
|
|
|
|
// `telnet 127.0.0.1 12345`
|
|
|
|
fn handle_connection(con net.Socket) {
|
2020-07-04 13:10:48 +02:00
|
|
|
peer_ip := con.peer_ip() or {
|
|
|
|
'0.0.0.0'
|
|
|
|
}
|
|
|
|
eprintln('${peer_ip:16} | new client connected')
|
2020-03-28 18:10:48 +01:00
|
|
|
defer {
|
2020-07-04 13:10:48 +02:00
|
|
|
eprintln('${peer_ip:16} | closing connection...')
|
2020-03-28 18:10:48 +01:00
|
|
|
con.close() or { }
|
|
|
|
}
|
|
|
|
con.send_string("Welcome to V's TCP Echo server.\n") or {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
for {
|
|
|
|
line := con.read_line()
|
|
|
|
if line.len == 0 {
|
|
|
|
return
|
|
|
|
}
|
2020-07-04 13:10:48 +02:00
|
|
|
eprintln('${peer_ip:16} | received line: ' + line.trim_space())
|
2020-03-28 18:10:48 +01:00
|
|
|
con.send_string(line) or {
|
|
|
|
return
|
2020-03-28 10:21:22 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
server_port := 12345
|
|
|
|
eprintln('Starting an echo server, listening on port: $server_port')
|
|
|
|
server := net.listen(server_port) or {
|
|
|
|
panic(err)
|
|
|
|
}
|
2020-03-28 18:10:48 +01:00
|
|
|
for {
|
2020-03-28 10:21:22 +01:00
|
|
|
con := server.accept() or {
|
2020-03-28 18:10:48 +01:00
|
|
|
server.close() or { }
|
2020-03-28 10:21:22 +01:00
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
go handle_connection(con)
|
|
|
|
}
|
|
|
|
}
|