闲着无聊,写了一个 Rust 语言使用 std::net::UdpSocket
实现 UDP 报文的例子。
这个例子很简单,就是 UDP 收到客户端报文之后,把字符串反转一下回给客户端
use std::net::UdpSocket; use std::str; use std::io; use std::env; fn main() -> std::io::Result<()> { const SOCKET_ADDR_S: &str = "127.0.0.1:34254"; const SOCKET_ADDR_C: &str = "127.0.0.1:34253"; let args: Vec<String> = env::args().collect(); if args.len() < 2 { println!("usage lx c data"); return Ok(()) } println!("{:?}",args); if args[1] == "s" { let socket = UdpSocket::bind(SOCKET_ADDR_S)?; loop { let mut buf = [0u8;2048]; let(amt,src) = socket.recv_from(&mut buf)?; let buf = &mut buf[..amt-1]; println!("received size:{:?}",amt); println!("received:{}",str::from_utf8(&buf).expect("could not read buffer as string")); if buf == "q".as_bytes() { println!("quit!"); socket.send_to("q".as_bytes(),&src)?; break; } buf.reverse(); socket.send_to(buf,&src)?; } } else if args[1] == "c" { let socket = UdpSocket::bind(SOCKET_ADDR_C)?; let _ = socket.connect(SOCKET_ADDR_S); loop { let mut input = String::new(); let _ = io::stdin().read_line(&mut input); let _ = socket.send(input.as_bytes()); let mut buff = [0u8;2048]; let (amt,_) = socket.recv_from(&mut buff)?; let buff = &buff[..amt]; if buff == "q".as_bytes() { println!("quit!"); break; } println!("recv:{}",str::from_utf8(&buff).expect("Could not write buffer as string")); } } Ok(()) }
使用方式,饿,要先编译好,比如,编译为 udpdemo
, 然后
启动服务端
udpdemo s
启动客户端
udp demo c
发送数据
在客户端输入好你想发送的报文后按下回车键就会发送出去
目前尚无回复