mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
examples: add net_udp_server_and_client.v
This commit is contained in:
parent
2c4674eb42
commit
d57a9c419d
44
examples/net_udp_server_and_client.v
Normal file
44
examples/net_udp_server_and_client.v
Normal file
@ -0,0 +1,44 @@
|
||||
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()
|
||||
mut buf := []byte{len: 100}
|
||||
if is_server {
|
||||
println('UDP echo server, listening for udp packets on port: $port')
|
||||
mut c := net.listen_udp(port) ?
|
||||
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.')
|
||||
mut c := net.dial_udp('localhost', 'localhost:$port') ?
|
||||
for {
|
||||
mut line := os.input('client > ')
|
||||
match line {
|
||||
'' {
|
||||
line = '\n'
|
||||
}
|
||||
'exit' {
|
||||
println('goodbye.')
|
||||
exit(0)
|
||||
}
|
||||
else {}
|
||||
}
|
||||
c.write_str(line) ?
|
||||
read, _ := c.read(mut buf) ?
|
||||
println('server : ' + buf[0..read].bytestr())
|
||||
}
|
||||
}
|
||||
}
|
@ -3,10 +3,16 @@ module net
|
||||
import time
|
||||
|
||||
const (
|
||||
udp_default_read_timeout = 30 * time.second
|
||||
udp_default_write_timeout = 30 * time.second
|
||||
udp_default_read_timeout = time.second / 10
|
||||
udp_default_write_timeout = time.second / 10
|
||||
)
|
||||
|
||||
struct UdpSocket {
|
||||
handle int
|
||||
l Addr
|
||||
r ?Addr
|
||||
}
|
||||
|
||||
pub struct UdpConn {
|
||||
pub mut:
|
||||
sock UdpSocket
|
||||
@ -168,12 +174,6 @@ pub fn listen_udp(port int) ?&UdpConn {
|
||||
}
|
||||
}
|
||||
|
||||
struct UdpSocket {
|
||||
handle int
|
||||
l Addr
|
||||
r ?Addr
|
||||
}
|
||||
|
||||
fn new_udp_socket(local_port int) ?&UdpSocket {
|
||||
sockfd := socket_error(C.socket(SocketFamily.inet, SocketType.udp, 0)) ?
|
||||
mut s := &UdpSocket{
|
||||
|
Loading…
Reference in New Issue
Block a user