udp_server.rs 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // You can run this example from the root of the mio repo:
  2. // cargo run --example udp_server --features="os-poll net"
  3. use log::warn;
  4. use mio::{Events, Interest, Poll, Token};
  5. use std::io;
  6. // A token to allow us to identify which event is for the `UdpSocket`.
  7. const UDP_SOCKET: Token = Token(0);
  8. #[cfg(not(target_os = "wasi"))]
  9. fn main() -> io::Result<()> {
  10. use mio::net::UdpSocket;
  11. env_logger::init();
  12. // Create a poll instance.
  13. let mut poll = Poll::new()?;
  14. // Create storage for events. Since we will only register a single socket, a
  15. // capacity of 1 will do.
  16. let mut events = Events::with_capacity(1);
  17. // Setup the UDP socket.
  18. let addr = "127.0.0.1:9000".parse().unwrap();
  19. let mut socket = UdpSocket::bind(addr)?;
  20. // Register our socket with the token defined above and an interest in being
  21. // `READABLE`.
  22. poll.registry()
  23. .register(&mut socket, UDP_SOCKET, Interest::READABLE)?;
  24. println!("You can connect to the server using `nc`:");
  25. println!(" $ nc -u 127.0.0.1 9000");
  26. println!("Anything you type will be echoed back to you.");
  27. // Initialize a buffer for the UDP packet. We use the maximum size of a UDP
  28. // packet, which is the maximum value of 16 a bit integer.
  29. let mut buf = [0; 1 << 16];
  30. // Our event loop.
  31. loop {
  32. // Poll to check if we have events waiting for us.
  33. poll.poll(&mut events, None)?;
  34. // Process each event.
  35. for event in events.iter() {
  36. // Validate the token we registered our socket with,
  37. // in this example it will only ever be one but we
  38. // make sure it's valid none the less.
  39. match event.token() {
  40. UDP_SOCKET => loop {
  41. // In this loop we receive all packets queued for the socket.
  42. match socket.recv_from(&mut buf) {
  43. Ok((packet_size, source_address)) => {
  44. // Echo the data.
  45. socket.send_to(&buf[..packet_size], source_address)?;
  46. }
  47. Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
  48. // If we get a `WouldBlock` error we know our socket
  49. // has no more packets queued, so we can return to
  50. // polling and wait for some more.
  51. break;
  52. }
  53. Err(e) => {
  54. // If it was any other kind of error, something went
  55. // wrong and we terminate with an error.
  56. return Err(e);
  57. }
  58. }
  59. },
  60. _ => {
  61. // This should never happen as we only registered our
  62. // `UdpSocket` using the `UDP_SOCKET` token, but if it ever
  63. // does we'll log it.
  64. warn!("Got event for unexpected token: {:?}", event);
  65. }
  66. }
  67. }
  68. }
  69. }
  70. #[cfg(target_os = "wasi")]
  71. fn main() {
  72. panic!("can't bind to an address with wasi")
  73. }