UDP server

  1. use std::io;
  2. use std::net::UdpSocket;
  3. fn main() -> io::Result<()> {
  4. let socket = UdpSocket::bind("127.0.0.1:8080")?;
  5. loop {
  6. let mut buffer = [0u8; 1024];
  7. let (amt, src) = socket.recv_from(&mut buffer)?;
  8. println!("size: {}", amt);
  9. let buffer = &mut buffer[..amt];
  10. buffer.reverse();
  11. socket.send_to(&buffer, src)?;
  12. }
  13. }

UDP client

  1. use std::io;
  2. use std::net::UdpSocket;
  3. use std::str;
  4. fn main() -> io::Result<()> {
  5. let socket = UdpSocket::bind("127.0.0.1:8000")?;
  6. socket.connect("127.0.0.1:8080")?;
  7. loop {
  8. let mut input = String::new();
  9. io::stdin().read_line(&mut input)?;
  10. socket.send(input.as_bytes())?;
  11. let mut buffer = [0u8; 1024];
  12. let (amt, _) = socket.recv_from(&mut buffer)?;
  13. println!(
  14. "receive from server :{}",
  15. str::from_utf8(&buffer[..amt]).expect("Can not convert to utf8")
  16. );
  17. }
  18. }