UDP server
use std::io;
use std::net::UdpSocket;
fn main() -> io::Result<()> {
let socket = UdpSocket::bind("127.0.0.1:8080")?;
loop {
let mut buffer = [0u8; 1024];
let (amt, src) = socket.recv_from(&mut buffer)?;
println!("size: {}", amt);
let buffer = &mut buffer[..amt];
buffer.reverse();
socket.send_to(&buffer, src)?;
}
}
UDP client
use std::io;
use std::net::UdpSocket;
use std::str;
fn main() -> io::Result<()> {
let socket = UdpSocket::bind("127.0.0.1:8000")?;
socket.connect("127.0.0.1:8080")?;
loop {
let mut input = String::new();
io::stdin().read_line(&mut input)?;
socket.send(input.as_bytes())?;
let mut buffer = [0u8; 1024];
let (amt, _) = socket.recv_from(&mut buffer)?;
println!(
"receive from server :{}",
str::from_utf8(&buffer[..amt]).expect("Can not convert to utf8")
);
}
}