2021-02-02 11:36:51 +03:00
|
|
|
import os
|
|
|
|
import os.cmdline
|
|
|
|
import net
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
println('Usage: net_udp_server_and_client [-l] [-p 5000]')
|
|
|
|
println(' -l - act as a server and listen')
|
|
|
|
println(' -p XXXX - custom port number')
|
|
|
|
println('------------------------------------------')
|
|
|
|
is_server := '-l' in os.args
|
|
|
|
port := cmdline.option(os.args, '-p', '40001').int()
|
2022-04-15 15:35:35 +03:00
|
|
|
mut buf := []u8{len: 100}
|
2021-02-02 11:36:51 +03:00
|
|
|
if is_server {
|
|
|
|
println('UDP echo server, listening for udp packets on port: $port')
|
2022-10-16 09:28:57 +03:00
|
|
|
mut c := net.listen_udp(':$port')!
|
2021-02-02 11:36:51 +03:00
|
|
|
for {
|
|
|
|
read, addr := c.read(mut buf) or { continue }
|
|
|
|
println('received $read bytes from $addr')
|
|
|
|
c.write_to(addr, buf[..read]) or {
|
|
|
|
println('Server: connection dropped')
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
println('UDP client, sending packets to port: ${port}.\nType `exit` to exit.')
|
2022-10-16 09:28:57 +03:00
|
|
|
mut c := net.dial_udp('localhost:$port')!
|
2021-02-02 11:36:51 +03:00
|
|
|
for {
|
|
|
|
mut line := os.input('client > ')
|
|
|
|
match line {
|
|
|
|
'' {
|
|
|
|
line = '\n'
|
|
|
|
}
|
|
|
|
'exit' {
|
|
|
|
println('goodbye.')
|
|
|
|
exit(0)
|
|
|
|
}
|
|
|
|
else {}
|
|
|
|
}
|
2022-10-16 09:28:57 +03:00
|
|
|
c.write_string(line)!
|
|
|
|
read, _ := c.read(mut buf)!
|
2021-02-02 11:36:51 +03:00
|
|
|
println('server : ' + buf[0..read].bytestr())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|