1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
//! A more ergonomic Tokio-enabled UDP socket.
//!
//! In particular, attention is paid to the fact that a UDP socket can both
//! send and receive datagrams, and that a practical consumer would like to be
//! able to do both of these things, interleaved on the same socket, with
//! non-blocking I/O.
//!
//! See the [`UdpSocket`] struct documentation for more details.
//!
//! [`UdpSocket`]: struct.UdpSocket.html
//!
//! # Examples
//!
//! ```no_run
//! # extern crate futures;
//! # extern crate udpsocket2;
//! #
//! # use udpsocket2::UdpSocket;
//! #
//! # fn main() -> std::io::Result<()> {
//! #
//! # use futures::{Future, Stream};
//! # use futures::future::ok;
//! #
//! let socket = UdpSocket::bind("127.0.0.1:34254")?;
//! #
//! # tokio::run(ok(()).and_then(move |_| {
//!
//! 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(|_| ())
//! );
//! #
//! # Ok(())
//! #
//! # }).map_err(|_: std::io::Error| ()));
//! #
//! # Ok(())
//! # }
//! ```
#[macro_use]
extern crate futures;
extern crate tokio;
pub mod incoming;
pub mod send_to;
#[cfg(test)]
mod tests;
use std::io;
use std::net::{SocketAddr, ToSocketAddrs};
use std::sync::{Arc, Mutex};
use tokio::net::{UdpSocket as TokioUdpSocket};
use incoming::Incoming;
use send_to::{Send, SendTo};
/// An individual UDP datagram, either having been received or to be sent over
/// a UDP socket.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UdpDatagram {
/// The peer for this datagram: if it was received, the source, if it is
/// to be sent, the destination.
pub peer: SocketAddr,
/// The data content of the datagram.
pub data: Vec<u8>,
}
/// 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`].
///
/// [`bind`]: #method.bind
/// [`Stream`]: ../futures/stream/trait.Stream.html
/// [`incoming`]: #method.incoming
/// [`send_to`]: #method.send_to
///
/// # Examples
///
/// ```no_run
/// # extern crate futures;
/// # extern crate udpsocket2;
/// #
/// # use udpsocket2::UdpSocket;
/// #
/// # fn main() -> std::io::Result<()> {
/// #
/// # use futures::{Future, Stream};
/// # use futures::future::ok;
/// #
/// let socket = UdpSocket::bind("127.0.0.1:34254")?;
/// #
/// # tokio::run(ok(()).and_then(move |_| {
///
/// 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(|_| ())
/// );
/// #
/// # Ok(())
/// #
/// # }).map_err(|_: std::io::Error| ()));
/// #
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct UdpSocket {
socket: Arc<Mutex<TokioUdpSocket>>,
}
impl UdpSocket {
fn new(socket: TokioUdpSocket) -> UdpSocket {
UdpSocket { socket: Arc::new(Mutex::new(socket)) }
}
/// 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.
///
/// [`ToSocketAddrs`]: https://doc.rust-lang.org/std/net/trait.ToSocketAddrs.html
/// [`std::net::UdpSocket::bind`]: https://doc.rust-lang.org/std/net/struct.UdpSocket.html#method.bind
///
/// # Examples
///
/// ```no_run
/// # extern crate udpsocket2;
/// # use udpsocket2::UdpSocket;
/// #
/// # fn main() -> std::io::Result<()> {
/// #
/// let socket = UdpSocket::bind("127.0.0.1:34254")?;
/// #
/// # Ok(())
/// # }
/// ```
pub fn bind<Addrs: ToSocketAddrs>(addrs: Addrs) -> Result<UdpSocket, io::Error> {
each_addr(addrs, TokioUdpSocket::bind).map(UdpSocket::new)
}
/// 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.
///
/// [`UdpDatagram`]: struct.UdpDatagram.html
///
/// # Examples
///
/// ```no_run
/// # extern crate futures;
/// # extern crate udpsocket2;
/// #
/// # use udpsocket2::UdpSocket;
/// #
/// # fn main() -> std::io::Result<()> {
/// #
/// # use futures::{Future, Stream};
/// # use futures::future::ok;
/// #
/// # let socket = UdpSocket::bind("127.0.0.1:34254")?;
/// #
/// # tokio::run(ok(()).and_then(move |_| {
/// #
/// tokio::spawn(
/// socket.incoming()
/// .for_each(|datagram| { println!("{:?}", datagram); Ok(()) })
/// .map_err(|_| ())
/// );
/// #
/// # Ok(())
/// #
/// # }));
/// #
/// # Ok(())
/// # }
/// ```
pub fn incoming(&self) -> Incoming {
Incoming::new(self.socket.clone())
}
/// 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`].
///
/// [`send`]: #method.send
///
/// [`std::net::UdpSocket::send_to`]: https://doc.rust-lang.org/std/net/struct.UdpSocket.html#method.send_to
///
/// # Examples
///
/// ```no_run
/// # extern crate futures;
/// # extern crate udpsocket2;
/// #
/// # use udpsocket2::UdpSocket;
/// #
/// # fn main() -> std::io::Result<()> {
/// #
/// # use futures::{Future, Stream};
/// # use futures::future::ok;
/// #
/// # let socket = UdpSocket::bind("127.0.0.1:34254")?;
/// #
/// # tokio::run(ok(()).and_then(move |_| {
/// #
/// tokio::spawn(
/// socket.send_to(&[0xde, 0xad, 0xbe, 0xef], "127.0.0.1:34254")?
/// .map_err(|_| ())
/// );
/// #
/// # Ok(())
/// #
/// # }).map_err(|_: std::io::Error| ()));
/// #
/// # Ok(())
/// # }
/// ```
pub fn send_to<'a, Addr: ToSocketAddrs>(
&self, buffer: &'a [u8], addr: Addr
) ->
Result<SendTo<'a>, io::Error>
{
let addr = match addr.to_socket_addrs()?.next() {
Some(addr) => addr,
None => return Err(
io::Error::new(io::ErrorKind::InvalidInput,
"could not resolve to any addresses")
),
};
Ok(SendTo::new(self.socket.clone(), buffer, addr))
}
/// 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.
///
/// [`send_to`]: #method.send_to
///
/// # Examples
///
/// ```no_run
/// # extern crate futures;
/// # extern crate udpsocket2;
/// #
/// # use udpsocket2::UdpSocket;
/// #
/// # fn main() -> std::io::Result<()> {
/// #
/// # use futures::{Future, Stream};
/// # use futures::future::ok;
/// #
/// # let socket = UdpSocket::bind("127.0.0.1:34254")?;
/// #
/// # tokio::run(ok(()).and_then(move |_| {
/// #
/// tokio::spawn(
/// socket.incoming()
/// .map_err(|_| ())
/// .for_each(move |datagram| {
/// // echo!
/// socket.send(datagram)
/// .map_err(|_| ())
/// })
/// );
/// #
/// # Ok(())
/// #
/// # }));
/// #
/// # Ok(())
/// # }
/// ```
pub fn send(&self, datagram: UdpDatagram) -> Send {
Send::new(self.socket.clone(), datagram)
}
}
// the below is totally cribbed from std::net
fn each_addr<A: ToSocketAddrs, F, T>(addr: A, mut f: F) -> io::Result<T>
where F: FnMut(&SocketAddr) -> io::Result<T>
{
let mut last_err = None;
for addr in addr.to_socket_addrs()? {
match f(&addr) {
Ok(l) => return Ok(l),
Err(e) => last_err = Some(e),
}
}
Err(last_err.unwrap_or_else(|| {
io::Error::new(io::ErrorKind::InvalidInput,
"could not resolve to any addresses")
}))
}