std-method
UDP nonblocking receive
Return WouldBlock when no datagram is queued, rather than waiting. A readiness event can race with another consumer, so WouldBlock still needs handling. This fixture creates a fresh, empty local socket. Expected stdout (not executed): true Common mistake: Spinning indefinitely on an empty socket.
Formal Syntax & Structure
rust syntaxrust
socket.set_nonblocking(true); socket.recv_from(&mut buffer)Working Example
Example Snippetrust
fn main() { use std::net::{Ipv4Addr, UdpSocket}; let socket = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).unwrap(); socket.set_nonblocking(true).unwrap(); let mut b = [0; 8]; println!("{}", socket.recv_from(&mut b).unwrap_err().kind() == std::io::ErrorKind::WouldBlock);}