Struct udpsocket2::UdpSocket
source · pub struct UdpSocket { /* private fields */ }
Expand description
A UDP socket, using non-blocking I/O.
Intended to be used within a Tokio runtime, this offers a more ergonomic interface compared to the standard tokio::net::UdpSocket.
Bind to a socket with the bind
method. Receive datagrams as a
Stream
with incoming
, and send datagrams with send_to
.
Examples
let socket = UdpSocket::bind("127.0.0.1:34254")?;
tokio::spawn(
socket.incoming()
.for_each(|datagram| { println!("{:?}", datagram); Ok(()) })
.map_err(|_| ())
);
tokio::spawn(
socket.send_to(&[0xde, 0xad, 0xbe, 0xef], "127.0.0.1:34254")?
.map_err(|_| ())
);
Implementations§
source§impl UdpSocket
impl UdpSocket
sourcepub fn bind<Addrs: ToSocketAddrs>(addrs: Addrs) -> Result<UdpSocket, Error>
pub fn bind<Addrs: ToSocketAddrs>(addrs: Addrs) -> Result<UdpSocket, Error>
Creates a UDP socket from the given address.
The address parameter, which must implement ToSocketAddrs
, is
treated the same as for std::net::UdpSocket::bind
. See the
documentation there for details.
Returns an Err
in the case that address parsing fails.
Examples
let socket = UdpSocket::bind("127.0.0.1:34254")?;
sourcepub fn incoming(&self) -> Incoming
pub fn incoming(&self) -> Incoming
Returns a stream of datagrams received on this socket.
Each datagram in the stream is a UdpDatagram
struct with the body
of the datagram and the peer address it was received from.
Examples
tokio::spawn(
socket.incoming()
.for_each(|datagram| { println!("{:?}", datagram); Ok(()) })
.map_err(|_| ())
);
sourcepub fn send_to<'a, Addr: ToSocketAddrs>(
&self,
buffer: &'a [u8],
addr: Addr
) -> Result<SendTo<'a>, Error>
pub fn send_to<'a, Addr: ToSocketAddrs>(
&self,
buffer: &'a [u8],
addr: Addr
) -> Result<SendTo<'a>, Error>
Sends data to the given address via the socket.
If the address text parses correctly, returns Ok
of a future which
resolves when the datagram has been written. Returns Err
if an
address can’t be parsed.
Though addr
might resolve to multiple socket addresses, this will
only attempt to send to the first resolved address, to be consistent
with std::net::UdpSocket::send_to
.
If you’ll be sending more than one datagram, it’s better to use send
.
Examples
tokio::spawn(
socket.send_to(&[0xde, 0xad, 0xbe, 0xef], "127.0.0.1:34254")?
.map_err(|_| ())
);
sourcepub fn send(&self, datagram: UdpDatagram) -> Send
pub fn send(&self, datagram: UdpDatagram) -> Send
Sends a datagram to the given address via the socket.
Returns a future which resolves when the datagram has been written.
Use this method instead of send_to
to repeatedly send to a
peer without the address parsing overhead or risk of errors.
Examples
tokio::spawn(
socket.incoming()
.map_err(|_| ())
.for_each(move |datagram| {
// echo!
socket.send(datagram)
.map_err(|_| ())
})
);