pub struct UdpListener { /* private fields */ }Expand description
An I/O object representing a UDP socket listening for incoming connections.
This object can be converted into a stream of incoming connections for various forms of processing.
Implementations§
Source§impl UdpListener
impl UdpListener
Sourcepub async fn bind<A: ToSocketAddrs>(addr: A) -> Result<Self, Error>
pub async fn bind<A: ToSocketAddrs>(addr: A) -> Result<Self, Error>
Usage is exactly the same as tokio::net::TcpListener::bind
Examples found in repository?
examples/udp_datagram_echo.rs (line 6)
5async fn main() -> Result<()> {
6 let listener = UdpListener::bind("127.0.0.1:9000").await?;
7 println!("udp datagram echo server listening on 127.0.0.1:9000");
8
9 loop {
10 let (stream, addr) = listener.accept().await?;
11 println!("accepted udp peer: {addr}");
12
13 tokio::spawn(async move {
14 let (mut reader, writer) = stream.split();
15 loop {
16 let msg = match reader.recv_datagram().await {
17 Ok(msg) => msg,
18 Err(err) => {
19 println!("recv_datagram error: {err}");
20 return;
21 }
22 };
23 if let Err(err) = writer.send_datagram(&msg).await {
24 println!("send_datagram error: {err}");
25 return;
26 }
27 }
28 });
29 }
30}Sourcepub fn local_addr(&self) -> Result<SocketAddr>
pub fn local_addr(&self) -> Result<SocketAddr>
Returns the local address that this socket is bound to.
Sourcepub async fn accept(&self) -> Result<(UdpStream, SocketAddr)>
pub async fn accept(&self) -> Result<(UdpStream, SocketAddr)>
Accepts a new incoming UDP connection.
Examples found in repository?
examples/udp_datagram_echo.rs (line 10)
5async fn main() -> Result<()> {
6 let listener = UdpListener::bind("127.0.0.1:9000").await?;
7 println!("udp datagram echo server listening on 127.0.0.1:9000");
8
9 loop {
10 let (stream, addr) = listener.accept().await?;
11 println!("accepted udp peer: {addr}");
12
13 tokio::spawn(async move {
14 let (mut reader, writer) = stream.split();
15 loop {
16 let msg = match reader.recv_datagram().await {
17 Ok(msg) => msg,
18 Err(err) => {
19 println!("recv_datagram error: {err}");
20 return;
21 }
22 };
23 if let Err(err) = writer.send_datagram(&msg).await {
24 println!("send_datagram error: {err}");
25 return;
26 }
27 }
28 });
29 }
30}Trait Implementations§
Auto Trait Implementations§
impl Freeze for UdpListener
impl !RefUnwindSafe for UdpListener
impl Send for UdpListener
impl Sync for UdpListener
impl Unpin for UdpListener
impl !UnwindSafe for UdpListener
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more