Skip to content

Commit 04f27f0

Browse files
committed
Improve docs for UdpSocket::set_nonblocking.
Closes #44050.
1 parent b6055cb commit 04f27f0

File tree

1 file changed

+33
-4
lines changed

1 file changed

+33
-4
lines changed

src/libstd/net/udp.rs

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -721,16 +721,45 @@ impl UdpSocket {
721721

722722
/// Moves this UDP socket into or out of nonblocking mode.
723723
///
724-
/// On Unix this corresponds to calling fcntl, and on Windows this
725-
/// corresponds to calling ioctlsocket.
724+
/// This will result in `recv`, `recv_from`, `send`, and `send_to`
725+
/// operations becoming nonblocking, i.e. immediately returning from their
726+
/// calls. If the IO operation is successful, `Ok` is returned and no
727+
/// further action is required. If the IO operation could not be completed
728+
/// and needs to be retried, an error with kind
729+
/// [`io::ErrorKind::WouldBlock`] is returned.
730+
///
731+
/// On Unix platforms, calling this method corresponds to calling `fcntl`
732+
/// `FIONBIO`. On Windows calling this method corresponds to calling
733+
/// `ioctlsocket` `FIONBIO`.
734+
///
735+
/// [`io::ErrorKind::WouldBlock`]: ../io/enum.ErrorKind.html#variant.WouldBlock
726736
///
727737
/// # Examples
728738
///
739+
/// Create a UDP socket bound to `127.0.0.1:7878` and read bytes in
740+
/// nonblocking mode:
741+
///
729742
/// ```no_run
743+
/// use std::io;
730744
/// use std::net::UdpSocket;
731745
///
732-
/// let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
733-
/// socket.set_nonblocking(true).expect("set_nonblocking call failed");
746+
/// let socket = UdpSocket::bind("127.0.0.1:7878").unwrap();
747+
/// socket.set_nonblocking(true).unwrap();
748+
///
749+
/// # fn wait_for_fd() { unimplemented!() }
750+
/// let mut buf = [0; 10];
751+
/// let (num_bytes_read, _) = loop {
752+
/// match socket.recv_from(&mut buf) {
753+
/// Ok(n) => break n,
754+
/// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
755+
/// // wait until network socket is ready, typically implemented
756+
/// // via platform-specific APIs such as epoll or IOCP
757+
/// wait_for_fd();
758+
/// }
759+
/// Err(e) => panic!("encountered IO error: {}", e),
760+
/// }
761+
/// };
762+
/// println!("bytes: {:?}", &buf[..num_bytes_read]);
734763
/// ```
735764
#[stable(feature = "net2_mutators", since = "1.9.0")]
736765
pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {

0 commit comments

Comments
 (0)